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!
Hit this compiling a TS library with
compilePackages. A literalrequire('pkg')gets rewritten to an import, but a computedrequire(specifier)(non-literal arg) can't be rewritten statically — and there's no ambientrequirein the compiled output, so it throwsReferenceErrorat runtime.typeof requireis'undefined'in both the entry and the compiled package modules, andcreateRequire(import.meta.url)from a namedmoduleimport works — so there's an easy workaround. Could compiled modules expose acreateRequire-backedrequireso dynamicrequire()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.tsentry.tsperry compile entry.ts -o app && ./appprints:Thanks for the great work on this!