TypeScript结合package.json时导入导出功能异常问题求助
解决方案:TypeScript ES模块与package.json "type:module" 兼容问题
问题根源
当package.json设置"type":"module"时,Node.js会将所有.js文件视为ES模块,但你的TypeScript编译输出的代码仍使用了CommonJS的exports语法,导致模块规范冲突,抛出ReferenceError: exports is not defined。
步骤1:修正tsconfig.json配置
首先修复原配置的语法错误(末尾多余的}),并调整编译选项确保输出ES模块代码:
{ "compilerOptions": { "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true, "outDir": "./dist" // 指定编译输出目录,避免源文件和编译文件混淆 } }
module: NodeNext和moduleResolution: NodeNext会让TypeScript根据package.json的type字段自动适配编译输出的模块格式(这里会输出ES模块)outDir可选但推荐,方便管理编译后的文件
步骤2:确保导入路径符合ES模块要求
ES模块要求导入必须带完整扩展名,因此file2.ts中的导入语句保持不变即可:
import { sayHi } from './index.js'; sayHi();
(TypeScript会自动识别.js对应源文件的.ts,编译后路径会正确指向输出的.js文件)
步骤3:编译并运行代码
- 执行编译命令:
tsc
- 运行编译后的文件(假设输出到
dist目录):
node dist/file2.js
验证inquirer兼容性
安装inquirer后,直接在TS文件中导入即可正常使用,无需额外配置:
import inquirer from 'inquirer'; async function askQuestion() { const answer = await inquirer.prompt([ { type: 'input', name: 'name', message: 'Enter your name:' } ]); console.log(`Hello, ${answer.name}!`); } askQuestion();
内容的提问来源于stack exchange,提问作者Zahir Khan
相关产品推荐
相关产品推荐

