【问题标题】:How do I fix "Cannot find module" when importing files from custom absolute path?从自定义绝对路径导入文件时如何修复“找不到模块”?
【发布时间】:2022-01-20 02:46:43
【问题描述】:

我尝试使用 TypeScript 从头开始​​创建 NodeJS,并且文件结构如下:

my-project
|
|--node_modules
|--src
|   |--index.ts
|   |--test.ts
|
|--package.json
|--tsconfig.json
|--...

然后在tsconfig.json 中,我添加了baseUrlpaths 以允许绝对导入

{
  "compilerOptions": {
    "target": "ES5",                                 
    "lib": ["es5", "es6", "ESNext"],                                       
    "experimentalDecorators": true,                   
    "emitDecoratorMetadata": true,                    
    "module": "CommonJS",                                
    "moduleResolution": "Node",                      
    "baseUrl": ".",                                 
    "paths": {
      "@src/*": ["src/*"],
      "@root/*": ["*"]
    },                                                 
    "resolveJsonModule": true,  
    "sourceMap": true,                                
    "outDir": "./build",                                   
    "allowSyntheticDefaultImports": true,             
    "esModuleInterop": true,                             
    "forceConsistentCasingInFileNames": true,            
    "strict": true,                                     
    "skipLibCheck": true                                 
  },
  "exclude": ["node_modules", "build"]
}

我创建了这样的简单代码,VSCode 仍然检测到test.ts 并通过严格模式的 linter 检查。

// src/test.ts
export const a = 1;
// src/index.ts
import { a } from '@src/test'
console.log(a);

之后,我运行npx nodemon src/index.ts,终端显示错误:

Error: Cannot find module '@src/test'
Require stack:
- D:\self-project\typeorm-test\src\index.ts

我是否配置路径错误?有谁知道如何解决这个问题?

【问题讨论】:

    标签: node.js typescript tsconfig


    【解决方案1】:

    我能找到的唯一解决方法是安装 tsconfig-paths 作为开发依赖项:

    npm install --save-dev tsconfig-paths
    

    我还安装了ts-node 作为开发依赖项。然后在 package.json 的脚本中添加:

    "dev": "nodemon --exec npx ts-node -r tsconfig-paths/register 
    

    【讨论】:

      猜你喜欢
      • 2012-08-27
      • 2018-11-24
      • 1970-01-01
      • 2017-05-05
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多