The import
and export
statements in JavaScript are crucial for modularizing code, enabling developers to organize and structure their codebase into separate files or modules. This approach promotes code reusability, maintainability, and scalability in larger projects. With import
and export
, a developer can split the code into smaller, more manageable pieces, focusing on specific functionalities or components.
How to reproduce it
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script defer src="js/main.js"></script>
...
config.js
export const gameConfig = {
canvas: null,
ctx: null,
}
main.js
import { gameConfig } from "./config.js";
Solution
The “SyntaxError: Cannot use import statement outside a module” error occurs because the import
and export
statements are part of ES6 modules. They need to be used within a module context. To specify that a script should be treated as a module, use the type="module"
attribute in the <script>
tag.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script defer type="module" src="js/main.js"></script>
...