Cannot use import statement outside modules Cannot use import statement outside modules express express

Cannot use import statement outside modules


Since Node v12, you can use either the .mjs extension or set "type": "module" in your package.json.

And you need to run node with the --experimental-modules flag.

node --experimental-modules server.mjs

You can check the SO link

Or you can create .babelrc file in the root of your project.Add following (and any other babel presets you need, can be added in this file):

{    "presets": ["env"]}

Install babel-preset-env using

npm install babel-preset-envnpm install babel-cli -g# ORyarn add babel-preset-envyarn global add babel-cli

Now, go to the folder where your server.js file exists and

run using:

babel-node fileName.js

Or you can run using npm start by adding following code to your package.json file:

"scripts": {    "start": "babel-node server.js"}

There is a tutorial link for Set Up Next.js with a Custom Express Server + Typescript on a medium that will be very helpful for you.


The following solution worked for me;

  • install needed packages

    npm install nodemon @babel/core @babel/node @babel/preset-env -D

  • create a .babelrc file in the working directory and paste the following in it

    {"presets": ["@babel/preset-env" ]}
  • lastly, add the code below to "scripts" in package.json

    "dev": "nodemon —exec babel-node server.js"where server.js is your file in this case.

Hope this works :)


Here is the solution based on ts-next-express.

 npm i --save ts-node

create another config file for express because node is using common.js module but if you check the tsconfig.json you will see this:"module": "esnext"

tsconfig.server.json

{  "extends": "./tsconfig.json",  "compilerOptions": {    "module": "commonjs",    "outDir": "dist",    "noEmit": false  },  "include": ["server"]}

set the script as follow:

 "start": "ts-node --project tsconfig.server.json server.ts"