John savadkuhi
1 min readJun 10, 2020

--

Cannot use import statement outside a module

what is that and how can we solve it ?

you should know NodeJS doesn't support import statement at the present time and the old method to solve this problem is using the require("module") method.

there is a good way to use import in NodeJS project without any error and it is babel , with babel we can translate new Javascript features to old. for example babel translate import to require that is an old method in javascript for importing modules.

There is an Algorithm to use import in NodeJs follow steps bellow :

in Linux and Mac OS :

1: create project directory with test name > mkdir test and then change directory to test > cd test

2 : install all related packages >

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

3 : create .babelrc in test directory > touch .babelrc

4 : add some code to .babelrc >

{

"presets": [

"@babel/preset-env" ]

}

5 : open the package.json and add bellow code to scripts >

"scripts": {

"dev": "nodemon — exec babel-node index.js"

}

6 : and then > npm run dev

after doing that Algorithm then you can use import instead require() without any Error .

--

--