[Solved] "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6
Problem:
I am new at nodejs. I was trying to learn something from a youtube tutorial. When I try to import an npm package, I got the following error:
"Uncaught SyntaxError: Cannot use import statement outside a module"
when importing ECMAScript
this is my file:
import { ms } from "./ms.js";
import Symbol from "./ms/symbol.js";
ms.Symbol = Symbol;
export { ms };
What is the right way to import a package?
So in this article, we are going to solve your problem.
Solution:
These are the three solutions you can do to solve your problem:
1. replace "import" and use "require" instead.
const ms = require("ms");
2. If you are using script you can include type="module " to solve this:
<script type="module" src="milsymbol-2.0.0/src/milsymbol.js"></script>
3. And the third solution is, add "type": "module" into your package.json file:
{
// ...
"type": "module",
// ...
}
Hopes this solves the problem you are having. If you have any more question you can comment below.