简体   繁体   中英

Cannot use import statement outside a module using typescript on backend

Currently using TypeScript on a Node backend, but I keep getting the following error when I attempt to import my mongoDB model:

(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)

My package.json currently looks like this:

{
  "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"
  }
}

and the tsconfig file looks like this:

{
  "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
}

As of now I've tried:

  1. Adding "type":"module" to my package.json folder
  2. Changing my "module" to esnext/commonjs and/or changing my target to esnext/es6/es2020

In your package.json add:

"type": "module"

just below "main": "index.js",

try adding typescript as dev dependency

npm install typescript --save-dev

also change module property to commonjs in tsconfig.json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM