Skip to content

compilePackages: computed require(expr) throws ReferenceError (createRequire works) #5373

@jdalton

Description

@jdalton

Hit this compiling a TS library with compilePackages. A literal require('pkg') gets rewritten to an import, but a computed require(specifier) (non-literal arg) can't be rewritten statically — and there's no ambient require in the compiled output, so it throws ReferenceError at runtime.

typeof require is 'undefined' in both the entry and the compiled package modules, and createRequire(import.meta.url) from a named module import works — so there's an easy workaround. Could compiled modules expose a createRequire-backed require so dynamic require() keeps working out of the box?

Minimal repro

package.json

{ "name": "app", "private": true, "perry": { "compilePackages": ["mylib"], "allow": { "compilePackages": ["mylib"] } } }

node_modules/mylib/package.json

{ "name": "mylib", "version": "1.0.0", "main": "./src/index.ts", "exports": { ".": "./src/index.ts" } }

node_modules/mylib/src/index.ts

import { createRequire } from 'module'

export function probe(): string {
  const spec = ['n', 'o', 'd', 'e', ':', 'o', 's'].join('') // computed -> not rewritable
  let viaRequire: string
  try {
    require(spec)
    viaRequire = 'require(computed) ok'
  } catch (e) {
    viaRequire = 'require(computed) threw ' + (e as Error).name
  }
  const req = createRequire(import.meta.url)
  return `typeof require=${typeof require} | ${viaRequire} | createRequire=${typeof req(spec)}`
}

entry.ts

import { probe } from 'mylib'

throw new Error(probe())

perry compile entry.ts -o app && ./app prints:

typeof require=undefined | require(computed) threw ReferenceError | createRequire=function

Thanks for the great work on this!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions