There are a few different ways to use JavaScript modules but one of the most widespread approaches is EcmaScript modules, often referred to simply as ES modules. This syntax uses the import
and export
statements. While relatively simple to use, you may still run into errors such as the Cannot use import statements outside a module
error.
You may encounter this issue whenever you try to use an import
statement.
This includes importing local modules or modules in installed packages. For example:
// javascript.js
import { add } from "./util.js"; // local module
import date from "date-and-time"; // npm module
const sum = add(1, 2);
const formattedDate = date.format(new Date(), "YYYY/MM/DD");
console.log(sum);
console.log(formattedDate);
Code language: JavaScript (javascript)
If I try to run this JavaScript file using node I may receive the Cannot use import statement outside a module
error despite everything in that file being correct.
Before we continue, make sure the modules you are trying to use are setup properly. In the example above, make sure the add
function is declared and exported correctly. Ensure that the date-and-time
module is properly installed. With that out of the way, the solution for the error should be quite simple. You will need to add a type
entry to your package.json
:
// package.json
{
// rest of your file
"type": "module"
}
Code language: JSON / JSON with Comments (json)
If you do not have a package.json
file but you are using node, you can create one using
npm init
or yarn init
depending on the package manager of your preference.
You may be importing a script into an html
file in which case, instead of a package.json
file, you’ll need to add the type
parameter to your script import:
<script src="javascript.js" type="module"></script>
Code language: HTML, XML (xml)
Give these solutions a try and you should no longer have to deal with that error. If not, feel free to leave a comment here and we will try our best to figure out a solution that works for you. Otherwise, have a great day and thanks for reading!