register
register copied to clipboard
swc-node doesn't work if child_process.fork is used in .ts
Hello! When I try to run my typescript file which contains child_process.fork using swc-node I get the following error:
//main.ts
child_process.fork(__dirname + '/testsRunner/testsRunner.js', args, {cwd: process.cwd()})
internal/modules/cjs/loader.js:1023
throw err;
^
Error: Cannot find module 'C:\src\testsRunner\testsRunner.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:1020:15)
at Function.Module._load (internal/modules/cjs/loader.js:890:27)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
It is because .js file doesn't really exist it supposed to be compiled on the fly. There is only testsRunner.ts file. Is there a way to get it working?
You should create a js file which imports @swc/register
and then testRunner.ts
@kdy1 Thank you for quick responce! Is there a way to make it without .js file?
You can use -r option of node itself to load @swc/register
like node -r @swc/register path/to/your/file.ts
, but I'm not sure if fork()
supports it.
If it doen't support it, you can use spawn()
instead
@kdy1 Unfortunately it doesn't work will try to use spawn thanks.
@kdy1 Worker threads are also unsupported. Is there any plans to support these features fork and threads? Is it ever possible in swc-node?
@niyarlatotep I want to support it, but I'm not sure if it is possible. Note that swc uses all cpu cores if you use async api and it does not block javascript thread. Almost all computations are done in the other threads.
@kdy1 I understand, I use threads and forks for other purposes not connected with swc itself. I just wanted to use swc instead of ts-node (which I see also doesn't support forks and therads) as much more faster alternative. In any case thank you for such a great work!
As long as your child process calls do not override env variables, setting NODE_OPTIONS=-r @swc/register
should suffice. Having this library automatically augment process.env.NODE_OPTIONS
at runtime might cause issues with other libraries using child processes.
@kherock thank you! I'll try it.