Description
Hi everyone,
I have encountered a problem where js
files are not properly processed by the register
if they are ESM modules. More specifically path aliases are not being replaced. In ts
files this seems to be working, however in js
files they are not being picked up.
You can find a reproducible example here. I am locking the core version to 1.3.105 in the example because of this issue, however I don't think they are related.
When building through swc into dist and then running the project, everything is working and js
files are being picked up and the path aliases are being replaced, but not through node register.
-- works
npx swc -d ./dist -D --delete-dir-on-start --only="**/*.js,**/*.ts,**/*.cjs,**/*.mjs" --ignore ./node_modules,./dist .
node dist/projects/api/main.js
-- doesn't work
SWCRC=true node --import=@swc-node/register/esm-register projects/api/main.ts
Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@foo/common' imported from workspaces/libs/math/src/foo.js
The latest version of swc-node
seems to be ignoring the paths
and baseUrl
on purpose here. Previous versions don't seem to pick up js
files anyway.
A potential fix is the following load function implementation:
export const load: LoadFn = async (url, context, nextLoad) => {
if (context.format === 'ts' || (tsconfig.allowJs && context.format === 'module')) { <<-- condition changed to include module
const { source } = await nextLoad(url, context)
const code = typeof source === 'string' ? source : Buffer.from(source).toString()
const compiled = await compile(code, fileURLToPath(url), tsconfig, true) <<-- pass tsconfig with paths and baseurl
return {
format: 'module',
source: compiled,
shortCircuit: true,
}
} else {
return nextLoad(url, context)
}
}
Is this a valid solution and if so, can we get it merged?