0

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
1
  • missing typescript as a dependency in package.json, and I'm not sure tsconfig is perfect or not because it should have a baseUrl or rootDir Commented Dec 26, 2020 at 11:45

2 Answers 2

1

In your package.json add :

"type": "module"

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

Sign up to request clarification or add additional context in comments.

Comments

0

try adding typescript as dev dependency

npm install typescript --save-dev

also change module property to commonjs in tsconfig.json

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.