【发布时间】:2020-12-27 15:06:43
【问题描述】:
目前在 Node 后端使用 TypeScript,但是当我尝试导入我的 mongoDB 模型时,我不断收到以下错误:
(node:47933) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
import Users from './models/Login';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:979:16)
at Module._compile (internal/modules/cjs/loader.js:1027:27)
我的 package.json 目前看起来像这样:
{
"name": "backend",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"bcrypt": "^5.0.0",
"cookie-session": "^1.4.0",
"express": "^4.17.1",
"mongoose": "^5.11.8",
"node-ts": "^5.1.1",
"passport": "^0.4.1",
"passport-facebook": "^3.0.0",
"passport-local": "^1.0.0"
},
"scripts": {
"server": "nodemon server.ts"
},
"devDependencies": {
"@types/bcrypt": "^3.0.0",
"@types/express": "^4.17.9",
"@types/mongoose": "^5.10.3",
"@types/node": "^14.14.14",
"@types/passport": "^1.0.4",
"dotenv": "^8.2.0",
"nodemon": "^2.0.6",
"ts-node": "^9.1.1"
}
}
tsconfig 文件如下所示:
{
"compilerOptions": {
/* Basic Options */
"module": "esnext",
"target": "ES2018",
"outDir": "./dist",
/* Strict Type-Checking Options */
"strict": true,
"esModuleInterop": true,
/* Source Map Options */
"inlineSourceMap": true,
"noImplicitAny": false
},
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true
}
到目前为止,我已经尝试过:
- 将“type”:“module”添加到我的 package.json 文件夹中
- 将我的“模块”更改为 esnext/commonjs 和/或将我的目标更改为 esnext/es6/es2020
【问题讨论】:
-
缺少
typescript作为 package.json 中的依赖项,我不确定 tsconfig 是否完美,因为它应该有baseUrl或rootDir
标签: javascript node.js typescript node-modules