I was trying to load some JS files and ran into this strange "Cannot use import statement outside of a module" error and couldn't keep up with the encoding. After doing some research, I found some solutions to fix the problem. Hope this helps you fix the import statement Cannot be used outside of a module node problem.
The simplest solution to the problem
importdeclaration is used to import links that are exported by another module.
The imported modules are in whether strictmode you declare them as such or not.
importdeclaration cannot be used in embedded scripts unless the script has
type="module". Here is an example for the import declaration with the type module.
<script type="module" src="app.js"></script>
# If it is not a module i.e. simple script
# you can use the nomodule tag
<script nomodule src="classic-app-bundle.js"></script>
There are many reasons for the problem mentioned above to occur. For example, you can get a file in the
srcdirectory instead of the file created in the
This means that are using the native source in unaltered / unbundled state, which leads to the following error:
Uncaught SyntaxError: Cannot use import statement outside a module. You can solve the problem by creating the script file and importing them.
Another problem could be that you are loading a file that you use
jsfiles, you need to compile the first
es6and then load the files to fix the problem
I got this error because I forgot the type = "module" inside the script tag, so this is how I fixed the problem:
<script type="module" src="source/to/file.js"></script>
I just added the type = "module" with the script tag and the problem was solved.
The error could be triggered if the file you are linking to in your HTML file is the disaggregated version of the file. To get the full version included, you will need to install it with
npm install --save package_to_save
When you run the above command, you will save the package in the node_modules directory and then you can link the file in
Verify that you have the latest version of Node.
If you have the latest version of the node, then
--experimental-modulesthe flag is no longer needed.
Just do any of the following to fix the problem:
"type": "module"the closest parent
package.json. With this, everything
.mjsfiles are interpreted as ES modules. You can interpret individual files as CommonJS by using the
- Explicitly name files with the
.mjsextension. All other files, as it will
.jsbe interpreted as CommonJS, which is the default if
typenot defined in