【问题标题】:Cannot use import statement outside a module using typescript on backend无法在后端使用 typescript 的模块外部使用 import 语句
【发布时间】: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
}

到目前为止,我已经尝试过:

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

【问题讨论】:

  • 缺少 typescript 作为 package.json 中的依赖项,我不确定 tsconfig 是否完美,因为它应该有 baseUrlrootDir

标签: javascript node.js typescript node-modules


【解决方案1】:

在你的 package.json 中添加:

"type": "module"

就在"main": "index.js",下方

【讨论】:

    【解决方案2】:

    尝试将 typescript 添加为开发依赖项

    npm install typescript --save-dev
    

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

    【讨论】:

      猜你喜欢
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-01
      • 2021-04-01
      • 2022-11-02
      • 2022-06-13
      • 2021-08-05
      相关资源
      最近更新 更多