Solved - SyntaxError Cannot use import statement outside a module
November 07, 2020
SyntaxError: Cannot use import statement outside a module
This is one of the most common issue if you are trying to use ES6 features in your JavaScript project.
For example, if I use the below statement in one of my npm project :
import fs from 'fs'
It will throw this error.
import csv from "csv-parser"
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1063:16)
at Module._compile (internal/modules/cjs/loader.js:1111:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10)
at Module.load (internal/modules/cjs/loader.js:996:32)
at Function.Module._load (internal/modules/cjs/loader.js:896:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
It also shows one warning :
Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
Solution :
In your package.json file, simply add “type”:“module” to fix this issue :
Or you can add the below line in your main entry JS file:
<script type="module" src="main.js"></script>
That’s it.