tsconfig-paths icon indicating copy to clipboard operation
tsconfig-paths copied to clipboard

node Cluster with tsconfig-paths

Open progral opened this issue 7 years ago • 3 comments

I have basically this folder structure for my project:

  • client (an angular app)
  • server (my backend app for node)
  • shared (mainly interfaces for client and server)
    • src
      • someModule.ts

I import things from shared folder into client and server with the paths section in tsconfig.json.

import { foo } from 'shared/someModule'

this works great if I start my app with

ts-node -r tsconfig-paths/register ./src/server.ts

But it totally fails with an module not found error if I use a cluster wrapper like this:

ts-node -r tsconfig-paths/register ./src/main.ts

where main.ts loads server.ts

import * as Cluster from "cluster";
const NUM_WORKERS = 2;

if (Cluster.isMaster) {
    console.info('Master cluster setting up ' + NUM_WORKERS + ' workers...');

    for (var i = 0; i < NUM_WORKERS; i++) {
        Cluster.fork();
    }
} else {

    //start server application    
    import('./server').then(() => {
        console.log("server started")
    });
}

Perhaps I doing it wrong, but it looks like tsconfig-path do not give it's "magic" to the workers. Is there a way we can handle this?

progral avatar Jan 03 '18 13:01 progral

Ok I found out that you have to have to configure your Cluster for ts-node and tsconfig-path this way:

cluster.setupMaster({
    execArgv: [ './node_modules/.bin/ts-node', '-r', 'tsconfig-paths/register' ],
    exec: './src/server.ts',
})

//..later
cluster.fork() 

Just a hint: types/node has an error with Cluster.setupMaster, at the moment but I have corrected it already and made an PR for DefinitelyTyped repo. PR

progral avatar Jan 03 '18 15:01 progral

It's not related to cluster specifically. In any module forked from the main process with child_process.fork('./worker') any imports using path aliases will not work.

Of course it's 'fixable' with ad hoc solution like above (by the way please don't hardcode things without need, you could as well have used execArgv: [ process.argv0, '-r', 'tsconfig-paths/register' ]) but it's far from elegant.

Perhaps tsconfig-paths could monkey patch child_process.fork on load? For backwards compatibility this could at least be enabled with a environment variable, such as TSCONFIG_PATCH_FORK=1.

IlyaSemenov avatar Aug 06 '18 04:08 IlyaSemenov

What is worsening things is that the behaviour is inconsistent between ts-node and ts-node-dev: https://github.com/whitecolor/ts-node-dev/issues/26

IlyaSemenov avatar Aug 07 '18 06:08 IlyaSemenov