swc-project / swc-node

Faster ts-node without typecheck
MIT License
1.69k stars 69 forks source link

Sourcemaps are broken for @swc-node/register/esm #719

Closed jwalton closed 4 days ago

jwalton commented 11 months ago

index.ts:

function main() {

    // Some whitespace for swc to optimize away...

    console.log('hello world');
    throw new Error('foo');
}

main()

@swc-node/register gives us sourcemap support:

$ node -r @swc-node/register ./index.ts
hello world
/Users/jwalton/t/index.ts:4
    throw new Error('foo');
    ^

Error: foo
    at main (/Users/jwalton/t/index.ts:7:11)

But @swc-node/register/esm does not:

node --loader @swc-node/register/esm ./index.ts
(node:81567) ExperimentalWarning: Custom ESM Loaders is an experimental feature and might change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
hello world
file:///Users/jwalton/t/index.ts.mjs:3
    throw new Error('foo');
          ^

Error: foo
    at main (file:///Users/jwalton/t/index.ts.mjs:3:11)
arimgibson commented 11 months ago

This also impacts debugging through VSCode's built in debugger, which relies on sourcemaps.

Xinkai commented 8 months ago

This finally bothered me enough so I took a look.

Finding: Unlike https://github.com/swc-project/swc-node/blob/e34f006484d89c53dd4cac7cface3c4d70841e34/packages/register/register.ts#L115, esm.mts does not call the installSourceMapSupport to enable source map support.

I then tried adding the following in esm.mts, as documented at https://nodejs.org/docs/latest-v20.x/api/module.html#initialize. Sadly, it does not work.

export async function initialize() {
    console.log("This function is indeed called without error, but source map does not apply");
    installSourceMapSupport();
}

Solution: I finally found this to be working (tested on Node 20). https://nodejs.org/docs/latest-v20.x/api/module.html#source-map-v3-support.

$ node --enable-source-maps --loader @swc-node/register/esm index.ts
slavafomin commented 6 months ago

Yep, stumbled upon this too.

@Xinkai thank you for a great workaround.

Happy new year :)