解决npm start报错:Must use import to load ES Module问题
解决TypeScript+Express项目启动时的ES模块加载错误
启动npm start时出现错误:
[ERROR] 12:16:18 Error: Must use import to load ES Module: /Users/kiryl/Documents/tic-tac-toe/src/index.ts
已尝试在package.json添加"type": "module"、将.eslintrc.js重命名为.eslintrc.json,但问题未解决。
现有配置文件
.eslintrc.js
module.exports = { "env": { "browser": true, "es2021": true }, "extends": [ "eslint:recommended", "plugin:@typescript-eslint/recommended" ], "overrides": [ ], "parser": "@typescript-eslint/parser", "parserOptions": { "ecmaVersion": "latest", "sourceType": "module" }, "plugins": [ "@typescript-eslint" ], "rules": { } }
package.json
{ "name": "tic-tac-toe", "version": "1.0.0", "description": "", "type": "module", "main": "index.js", "scripts": { "lint": "eslint . --ext .ts", "format": "eslint src/**/*.ts --fix", "start": "ts-node-dev src/index.ts", "build": "tsc --build" }, "repository": { "type": "git", "url": "git+https://github.com/kirillleogky/tic-tac-toe.git" }, "author": "", "license": "ISC", "bugs": { "url": "https://github.com/kirillleogky/tic-tac-toe/issues" }, "homepage": "https://github.com/kirillleogky/tic-tac-toe#readme", "devDependencies": { "@types/express": "^4.17.14", "@types/node": "^18.11.10", "@typescript-eslint/eslint-plugin": "^5.45.0", "@typescript-eslint/parser": "^5.45.0", "eslint": "^8.29.0", "ts-node-dev": "^2.0.0", "typescript": "^4.9.3" }, "dependencies": { "ejs": "^3.1.8", "express": "^4.18.2" } }
tsconfig.json
{ "compilerOptions": { "module": "es6", "esModuleInterop": true, "target": "es6", "forceConsistentCasingInFileNames": true, "moduleResolution": "node", "sourceMap": true, "outDir": "dist", }, "include": [ "./src", ], }
src/index.ts
import express from 'express'; const app = express(); const port = 3000; app.use(express.json()); app.use(express.static("public")); app.set("view engine", "ejs"); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { return console.log(`http://localhost:${port}`); });
有效解决方案
1. 调整ts-node-dev启动参数
修改package.json中的start脚本,添加--esm参数以启用ES模块支持:
"scripts": { "start": "ts-node-dev --esm src/index.ts" }
2. 更新tsconfig.json配置
修改compilerOptions中的module和moduleResolution,适配Node.js的ES模块解析规则:
"compilerOptions": { "module": "ESNext", "moduleResolution": "nodenext", // 其余原有配置保留 }
3. 修正ESLint配置文件格式(可选)
如果继续使用JS格式的ESLint配置,需将.eslintrc.js重命名为.eslintrc.cjs,因为type:module模式下,JS文件默认被识别为ES模块,无法使用module.exports。若已改为.eslintrc.json则无需此步骤。
内容的提问来源于stack exchange,提问作者Kirill Margheriti
相关产品推荐
相关产品推荐

