使用ts-node出现Uncaught SyntaxError: Unexpected token 'export'错误怎么办?
问题:ts-node REPL中ES模块导入失败,如何修复配置?
场景与代码
我尝试根据NODE_ENV加载不同环境配置,./config/env/config.ts代码如下:
import path from 'path'; export default await import(`./${process.env.NODE_ENV || 'development'}`).then((env) => { const defaults = { root: path.join(path.dirname('.'), '/..'), api: { title: 'API: Users and Application Resources', version: '0.0.1', description: 'A RESTful API for managing users and application resources.', }, fileSizeLimit: 10 * 1024 * 1024, }; return Object.assign(env, defaults); });
运行npx ts-node进入REPL后,执行import config from './config/env'时出现错误,甚至执行import dotenv from 'dotenv';也会报相同错误。我的tsconfig.json配置如下:
{ "compilerOptions": { "module": "ES2022", "target": "ES2022", "outDir": "bin", "rootDir": "/", "strict": true, "noImplicitAny": true, "strictNullChecks": true, "checkJs": true, "allowJs": true, "moduleResolution": "node", "types": ["node", "mocha", "chai"], "typeRoots": ["node_modules/@types"], "lib": ["ES2022"], "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "allowUnreachableCode": true, "useUnknownInCatchVariables": false }, "ts-node": { "esm": true, "compilerOptions": { "module": "ES2022" } }, "include": [ "app/**/*.ts", "config/**/*.ts", "test/**/*.ts" ], "exclude": ["node_modules", "<node_internals>/**", "./built/**/*"] }
修复方案
1. 配置package.json的模块类型
在项目根目录的package.json中添加"type": "module"字段,明确告知Node.js当前项目采用ES模块规范:
{ "type": "module" }
2. 优化ts-node配置
在tsconfig.json的ts-node字段中添加experimentalSpecifierResolution: "node",让模块解析兼容Node.js的路径规则(比如允许省略文件扩展名):
"ts-node": { "esm": true, "experimentalSpecifierResolution": "node", "compilerOptions": { "module": "ES2022" } }
3. 修复config文件的路径问题
ES模块中无法使用__dirname,需要替换为import.meta.url来获取当前文件路径,修正root字段的计算:
// 替换原root字段的写法 const __dirname = path.dirname(new URL(import.meta.url).pathname); const defaults = { root: path.join(__dirname, '/..'), // ...其他配置 };
同时确保动态导入的目标文件(比如development.ts)存在,且采用ES模块格式导出(使用export default导出配置对象)。
4. 调整tsconfig的模块解析策略
将compilerOptions中的moduleResolution从node改为bundler,更适配ES模块的解析逻辑:
"moduleResolution": "bundler"
5. REPL中的正确导入路径
在ts-node REPL中导入时,确保路径与文件实际位置匹配,比如从项目根目录导入时,使用完整的相对路径(可省略.ts扩展名,依赖上述配置):
import config from './config/env/config';
内容的提问来源于stack exchange,提问作者mkelley33
相关产品推荐
相关产品推荐

