9

I had meet the problem that resolve non-relative moduels in typescript. And try baseUrl, paths and so on, but it not works....

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "baseUrl": ".",
    "esModuleInterop": true,
    "module": "commonjs",
    "sourceMap": true,
    "strict": true,
    "target": "esnext",
    "typeRoots": ["node_modules/@types"]
 }
}

The project dirs:

root
  ├─src
    ├── APIs
    ├── config
    ├── constants
    ├── middlewares
    ├── models
    ├── routes
    ├── services
          - foo.ts   
    ├── utils
    └── app.ts

in app.ts

import foo from 'src/services/foo'

And run with ts-node src/app.ts.

But the error occurs:

Cannot find module 'src/services/foo'
junlin
  • 1,835
  • 2
  • 25
  • 38

2 Answers2

4

Finally, I add paths option to resolve it.

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "removeComments": true,
    "sourceMap": true,
    "target": "esnext",
    "strict": true,
    "noUnusedLocals": true,
    "paths": {
      "@/*": ["src/*"]
    },
    "typeRoots": ["./src/@types", "./node_modules/@types"]
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/node_modules/*", "**/*.spec.ts"]
}

In app.ts:

import foo from '@/services/foo'
junlin
  • 1,835
  • 2
  • 25
  • 38
1

You will need to add tsconfig-paths and module-alias to package.json like this:

    "_moduleDirectories:" ["src"]

And in app.ts use:

    import 'module-alias/register';

You will also need to create tsconfig-path.js file in your root directory that should look like this:

const tsConfigPaths = require('tsconfig-paths');
const tsConfig = require('./tsconfig.json');
tsConfigPaths.register({
    baseUrl: tsConfig.compilerOptions.outDir,
    paths: tsConfig.compilerOptions.paths,
});

Also change tsconfig.json:

{
    "compilerOptions": {
        "baseUrl": "src",
        "paths": {
            "*":["./*"]
        }
    },
    "exclude": ["node_modules"],
    "include": ["./src/**/*.ts"]
}
sanitizedUser
  • 1,723
  • 3
  • 18
  • 33