You need to enable JavaScript to run this app. Node.js+TypeScript无法导入本地模块,求排查解决方法
优惠活动
大模型
产品
解决方案
定价
更多

Node.js+TypeScript无法导入本地模块,求排查解决方法

Node.js + TypeScript 本地模块导入失败问题排查

问题场景

在Node.js项目中使用TypeScript时,导入本地JavaScript模块出现报错:

Cannot find module '/modules/date' or its corresponding type declarations.ts(2307)

相关代码

modules/date.js

const getDate = () => {...};
const getDay = () => {...};
export {getDate, getDay};

app.ts 导入代码

import {getDay, getDate} from "/modules/date";
// import {getDay, getDate} from "/modules/date.js"; 同样无法工作

配置文件

package.json

{  
  "dependencies": {    
    "ejs": "^3.1.8",    
    "express": "^4.18.2",    
    "mongoose": "^6.8.3",    
    "nodemon": "^2.0.20",    
    "typescript": "^4.9.4"  
  },  
  "name": "todolist",  
  "version": "1.0.0",  
  "description": "A simple todo list",  
  "main": "app.js",  
  "scripts": {    
    "test": "echo \"Error: no test specified\" && exit 1"  
  },  
  "author": "Infinite Learner",  
  "license": "ISC",  
  "devDependencies": {    
    "@types/express": "^4.17.15"  
  },  
  "type": "module"
}

tsconfig.json

{  
  "compilerOptions": {    
    "target": "es2016",                                  
    "lib": ["es6"],                                      

    /* Modules */    
    "moduleResolution": "node",    
    "rootDir": "./",                                     

    /* Emit */    
    "outDir": "build",                                   

    /* Interop Constraints */    
    "esModuleInterop": true,                             
    "forceConsistentCasingInFileNames": true,            

    /* Type Checking */    
    "strict": true,                                      

    /* Completeness */    
    "skipLibCheck": true                                 
  }
}

问题原因及解决步骤

  • 绝对路径错误
    /modules/date指向的是系统根目录,而非项目根目录。需改为相对路径(假设app.ts在项目根目录):

    import {getDay, getDate} from "./modules/date";
    
  • 缺失JS模块的类型声明
    TypeScript默认需要类型声明来识别JS模块,有两种解决方式:

    1. 在modules目录下创建date.d.ts类型声明文件:
      export declare function getDate(): string; // 根据实际返回类型调整
      export declare function getDay(): string; // 根据实际返回类型调整
      
    2. 在tsconfig.json的compilerOptions中添加"allowJs": true,让TypeScript直接处理JS文件。
  • ES模块与模块解析模式不匹配
    由于package.json设置了"type": "module",需调整tsconfig.json的模块配置以适配ES模块:

    "module": "ESNext",
    "moduleResolution": "nodenext"
    

    同时ES模块要求导入时明确后缀,建议修改导入语句为:

    import {getDay, getDate} from "./modules/date.js";
    

内容的提问来源于stack exchange,提问作者Infinite Learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 03:30:42