SyntaxError: Cannot use import statement outside a module in Nodejs
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.
- A2
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.
- M1
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" } }
- H0
Hoàng Nhật Duy Nguyễn Sep 25 2021
To solve this issue, you can try do as below:
- Add
"type": "module"
topackage.json
- Add the flag
"--experimental-modules"
to the invocation of the node
- Add
- P0
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 userequire()
and that bug is solved for me. - จ0
จักรพงษ์ รักษาศรี 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 yourpackage.json
I hope it helpful for you.
- Step 1: Change
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.