[Fixed] How to fix SyntaxError: Cannot use import statement outside a module?

Issue

I am new to all of this, and I’m trying to add Node + Typescript backend to my Angular project. But after importing express I always get the error.

[ERROR] SyntaxError: Cannot use import statement outside a module.

package.json

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "serve": "ts-node-dev server.ts",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/express": "^4.17.11",
    "express": "^4.17.1",
    "ts-node": "^9.1.1",
    "ts-node-dev": "^1.1.6",
    "tslint": "^6.1.3",
    "typescript": "^4.2.4"
  },
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNEXT",                                
    "module": "commonjs", 
    "strict": false, 
    "esModuleInterop": true, 
    "skipLibCheck": true,                          
    "forceConsistentCasingInFileNames": true        
  }
}   

server.ts

import * as express from 'express';

const app = express();

app.listen(4201, '127.0.0.', function() {
  console.log('Server is listening on port 4201');
});

I have looked this up and the most common solution was to add "type": "module" to package.json which I did. I also know that this works only from Node 13 and further, and I have Node: 14.15.5.

Solution

The best practice to import the node modules is by using require(). You can import built-in core node modules, npm modules as well as local modules using require() function. In your case, use const express = require( "express" ) instead of import * as express from 'express' and remove "type":"module" from your package.json. Let me know if this works for you.

Leave a Reply

(*) Required, Your email will not be published