TypeScript无法找到具有非相对路径“src/xxx”的模块

iovurdzv  于 2023-10-22  发布在  TypeScript
关注(0)|答案(3)|浏览(117)

我曾经遇到过解决打印稿中非相关模块的问题。然后尝试baseUrlpaths等等,但它不工作.

tsconfig.json

  1. {
  2. "compilerOptions": {
  3. "allowJs": true,
  4. "baseUrl": ".",
  5. "esModuleInterop": true,
  6. "module": "commonjs",
  7. "sourceMap": true,
  8. "strict": true,
  9. "target": "esnext",
  10. "typeRoots": ["node_modules/@types"]
  11. }
  12. }

项目负责人:

  1. root
  2. ├─src
  3. ├── APIs
  4. ├── config
  5. ├── constants
  6. ├── middlewares
  7. ├── models
  8. ├── routes
  9. ├── services
  10. - foo.ts
  11. ├── utils
  12. └── app.ts

app.ts

  1. import foo from 'src/services/foo'

运行ts-node src/app.ts
但是错误发生了:

  1. Cannot find module 'src/services/foo'
5tmbdcev

5tmbdcev1#

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

tsconfig.json

  1. {
  2. "compilerOptions": {
  3. "baseUrl": ".",
  4. "esModuleInterop": true,
  5. "module": "commonjs",
  6. "moduleResolution": "node",
  7. "removeComments": true,
  8. "sourceMap": true,
  9. "target": "esnext",
  10. "strict": true,
  11. "noUnusedLocals": true,
  12. "paths": {
  13. "@/*": ["src/*"]
  14. },
  15. "typeRoots": ["./src/@types", "./node_modules/@types"]
  16. },
  17. "include": ["src/**/*"],
  18. "exclude": ["node_modules", "**/node_modules/*", "**/*.spec.ts"]
  19. }

app.ts中:

  1. import foo from '@/services/foo'
展开查看全部
to94eoyn

to94eoyn2#

您需要像这样将tsconfig-pathsmodule-alias添加到 package.json 中:

  1. "_moduleDirectories:" ["src"]

app.ts 中使用:用途:

  1. import 'module-alias/register';

您还需要在根目录中创建 * tslog-path.js* 文件,该文件应该如下所示:

  1. const tsConfigPaths = require('tsconfig-paths');
  2. const tsConfig = require('./tsconfig.json');
  3. tsConfigPaths.register({
  4. baseUrl: tsConfig.compilerOptions.outDir,
  5. paths: tsConfig.compilerOptions.paths,
  6. });

同时更改 * tsconfig.json *:

  1. {
  2. "compilerOptions": {
  3. "baseUrl": "src",
  4. "paths": {
  5. "*":["./*"]
  6. }
  7. },
  8. "exclude": ["node_modules"],
  9. "include": ["./src/**/*.ts"]
  10. }
展开查看全部
ac1kyiln

ac1kyiln3#

你需要安装tsconfig-paths并在tsconfig.json文件中添加以下内容:

  1. "ts-node": {
  2. // Do not forget to `npm i -D tsconfig-paths`
  3. "require": ["tsconfig-paths/register"]
  4. }

参考:https://github.com/TypeStrong/ts-node#paths-and-baseurl

相关问题