TypeScript找不到具有非相对路径'src / xxx'

时间:2018-07-06 10:28:59

标签: typescript ts-node

我遇到了解决打字稿中非相对模数​​的问题。并尝试baseUrlpaths等,但不起作用。...

tsconfig.json

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

项目目录:

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

app.ts

import foo from 'src/services/foo'

并运行ts-node src/app.ts

但是发生错误:

Cannot find module 'src/services/foo'

1 个答案:

答案 0 :(得分:0)

最后,我添加了paths选项来解决它。

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"]
}

app.ts 中:

import foo from '@/services/foo'