cannot run compiled typescript prog using module resolution

59 Views Asked by At

I'm trying to compule the following typscript file

import { magic } from 'lib/magic';

magic();

The filestructure is:

./src/
     main.ts
     lib/
         a/magic.ts
         b/magic.ts

Inside tsconfig.json I map lib/magic to the right file as follows

{
    "compilerOptions": {
        "target": "esnext",
        "module": "commonjs",
        "outDir": "./dist",
        "baseUrl": ".",
        "paths": {
            "lib/*": [ "src/lib/a/*" ]
        }
    },
    "include": [ "./src/**/*.ts" ],
    "exclude": [ "./node_modules" ]
}

It is that paths section that maps that import lib/magic to ./src/lib/a/magic.ts.

So, I can compile as follows

$> tsc -p ./tsconfig-a.json

It produces output in dist. However, when I try to run it

$> node ./dist/main.js
internal/modules/cjs/loader.js:626
    throw err;
^

Error: Cannot find module 'lib/magic'
Require stack:
...

It makes sense, because in dist there is no such thing as lib/magic. Any suggestions how to fix this?

1

There are 1 best solutions below

0
On

Until someone proves me wrong, here are my findings so far.

Here is an issue in which it is stated that all this is in fact expected behaviour.

So you basically have to fix it in a second step. In my case I want to make 2 build, one for a and one for b. The easiest way to fix it then is to have it working by default for a as follows

import { magic } from './lib/a/magic';

magic();

Then build b and replace that path as follows

sed -e 's/lib\/a/lib\/b/' ./dist/main.js > ./dist/main-node.js

In my case, one version was for NodeJs and the other for the browser, so I also needed to add the .js extension. Just in case anyone is interested, here is the command

$> echo "import { magic } from  './lib/a/magic';" | sed "s#^\(import[^']*\)'\([^']*\)#\1 '\2.js#g" 

Please let me know if you have a better solution, because all this feels a bit hacky