typescript path alias needs module-alias/register on every file

10.7k views Asked by At

I am using typescript v3.6.4 with the following tsconfig.json snippet:


  "compilerOptions": {
    "moduleResolution": "node",
    "baseUrl": "./src",
    "paths": {
      "@config/*": ["config/*"],
      "@config": ["config"],
    }
  }

and module alias in package.json:

  "_moduleAliases": {
    "@config": "dist/config"
  }

I have the following folder structure:

src
 |-config
     |-index.ts
 |-app
     |index.ts
     |logic.ts
 |-dist

Now in app/index.ts, if I do:

import 'module-alias/register';
import config from '@config';

and my npm start commands is:

"start": "node -r ts-node/register ./src/app/index.ts",

tsc will compile successfully but npm start will give error:

Error: Cannot find module '@config' in src/app/logic.ts

And the only way to fix this is to also add

import 'module-alias/register';

in src/app/logic.ts

Seems I have to add the import 'module-alias/register' in every file that I do alias? Is it a way to configure this?

2

There are 2 answers

0
Gfast2 On

@2021

For me I've got exact the same issue: typescript allowed me only use the module aliasing when the every module has import 'module-alias/register'; at its top line when it has such module alias.

After spent nearly whole day, I got the point:

tsc won't help to transpiling these decorators. so you have to make sure every consumer of the js compiled code have acknoledged and know how to deal with these module imports with alias.

i.e.:

node index.js
=>
node -r module-alias/register index.js

///

mocha .
=>
mocha -r module-alias/register .
1
jamesdeath123 On

The solution to this is quite simple:

in the root file, like app/index.ts, put the import 'module-alias/register'; to the end of all the other imports and you won't need to put it in every file. It didn't work for me because I put that import before all other imports, not after.

For example:

import express from 'express';
import corsFilter from 'cors';
...
import 'module-alias/register'; // This has to be after all other imports