不能在后端使用打字稿的模块外使用 import 语句

时间:2020-12-26 11:36:16

标签: javascript node.js typescript node-modules

目前在 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
}

截至目前我已经尝试过:

  1. 将 "type":"module" 添加到我的 package.json 文件夹
  2. 将我的“模块”更改为 esnext/commonjs 和/或将我的目标更改为 esnext/es6/es2020

2 个答案:

答案 0 :(得分:1)

在你的 package.json 添加:

"type": "module"

刚好低于"main": "index.js",

答案 1 :(得分:0)

尝试添加 typescript 作为开发依赖

npm install typescript --save-dev

还将 tsconfig.json 中的 module 属性更改为 commonjs