SyntaxError: Cannot use import statement outside a module in Nodejs

Dung Do Tien Sep 25 2021 219

Hello you guys, I am a newbie in Nodejs and I'm also studying more about Nodejs.

I have some lines of code, I have create an server express and import it into index.js file. Function as below:

require('dotenv').config()
import {MainServer} from './server'
MainServer()

But I get an exception SyntaxError: Cannot use import statement outside a module when I run code above.

/home/runner/project-node/index.js:2
import {MainServer} from './server'
^^^^^^

SyntaxError: Cannot use import statement outside a module

tsconfig.json

{
    "compilerOptions": {
        "target": "ES2016",
        "module": "commonjs"
    }
}

And I am using Nodejs v12.22.6

Anyone can explain it to me? How can I solve it?

Thanks for any response.

Have 5 answer(s) found.
  • A

    Aleyna Bostan Sep 25 2021

    Please sure you update Nodejs to latest version (or at least 13.2.0+). 

    package.json add a top-level field "type" with a value to the closest parent file "module". This will ensure that all files are .js and .mjs will be interpreted as ES modules. 

    Open package.json and change as below:

    // package.json
    {
      "type": "module"
    }

    I hope it useful for you.

  • M

    Mario Guzmán Sep 27 2021

    You can change your tsconfig.json as below:

    {
      "ts-node": {
        // these options are overrides used only by ts-node
        // same as our --compilerOptions flag and our TS_NODE_COMPILER_OPTIONS environment variable
        "compilerOptions": {
          "module": "commonjs"
        }
      },
      "compilerOptions": {
        "module": "esnext"
      }
    }
    
  • H

    Hoàng Nhật Duy Nguyễn Sep 25 2021

    To solve this issue, you can try do as below:

    1. Add "type": "module" to package.json
    2. Add the flag "--experimental-modules" to the invocation of the node
  • P

    Phúc Lê Khắc Sep 27 2021

    I got the same error when I using import ... from to help import a package, and I change to use require() and that bug is solved for me.

  • จักรพงษ์ รักษาศรี Sep 27 2021

    You can try to change .js files extension to .mjs

    • Step 1: Change .js files extension to .mjs
    • Step 2: Add –experimental-modules flag upon running your app.
    • Step 3:  add "type": "module" in your package.json

     I hope it helpful for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close