node.jstypescripttsconfig

Using compilerOptions: paths does not work with node


Very similar to this question, but not a duplicate IMHO when using node:

$ tree .                                        
.
├── src
│   ├── main.ts
│   └── utils
│       └── myUtils.ts
└── tsconfig.json

I'm trying to use a @ import like so:

$ cat src/main.ts 
import { myLovelyUtilsFunction } from "@folder1/myUtils"
const y = myLovelyUtilsFunction();
console.log(`>>> ${y}`);

My tsconfig.json looks right, mapping @folder1 where it should:

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": { "@folder1/*": ["utils/*"] },
    "module": "commonjs"
  }
}

Transpilation goes fine, but running node doesn't:

$ npx tsc -p tsconfig.json # <--- no errors
$ node src/main.js
node:internal/modules/cjs/loader:1078
  throw err;
  ^

Error: Cannot find module '@folder1/myUtils'
Require stack:
< ... omitted ... > 

Solution

  • I think you need tsconfig-paths or ts-nodeto get your module resolution work properly.

    Modify your tsconfig.json

    {
      "compilerOptions": {
        "baseUrl": "./",
        "paths": { "@folder1/*": ["src/utils/*"] },
        "module": "commonjs"
      },
      "include": ["src/**/*"],
      "exclude": ["node_modules", "**/*.spec.ts"]
    }
    

    You also need to create an entry file point, which will use tsconfig-paths to resolve the paths.

    index.ts
    
    import 'tsconfig-paths/register';
    import './src/main';
    

    Update your package.json and then run to test.

    {
      "scripts": {
        "start": "node index.js"
      }
    }
    

    The structure of your project could look like this now

    .
    ├── src/
    │   ├── main.ts
    │   ├── utils/
    │   │   └── myUtils.ts
    ├── tsconfig.json
    ├── package.json
    ├── index.ts