Cannot use import statement outside a module
The browser attempted to compile ES module import statements in a script not declared as type="module".
Usually happens because:
- ☑ Script tag missing type="module" attribute
- ☑ Browser doesn't support ES Modules
- ☑ Classic script contains import statement
🔍 Quick Checklist:
📊 Where this usually happens (estimated occurrence)
What is Cannot use import statement outside a module?
This SyntaxError occurs when the browser's JavaScript engine parses ES6 import/export statements inside a file that is loaded as a classic script. To utilize imports, the script tag must carry the type="module" attribute.
Common Causes
- Script tag missing type="module" attribute in HTML.
- Using ESM syntax inside older browser engines lacking module capabilities.
- Bundler output conflicts leaving raw imports inside classic scripts.
Common Mistakes
- Omitting script type attributes when utilizing ES6 syntax directly in client files.
How to Fix
Framework-Specific Examples
Declaring scripts as modules inside HTML files.
<!-- Enables browser ESM support -->
<script type="module" src="app.js"></script>Server Configuration Examples
Webpack/Babel configurations.
# Handled at compiler compiler stageBest Practices
- Standardize on Webpack/Vite bundlers to target backwards-compatible builds.
Frequently Asked Questions (FAQ)
Q: Why do I need type="module"?
Because the JavaScript engine parses classic scripts and module scripts differently. Module scripts support ES6 features like `import` and `export` and execute in strict mode by default.
Q: Does type="module" defer script execution?
Yes. Module scripts are deferred automatically, meaning they execute only after the HTML document parser has finished loading.
Q: Can I use require() inside type="module"?
No. `require()` is a CommonJS module loader syntax and is not supported inside standard browser ES Modules. Use `import` instead.
Q: How do I resolve module paths?
Relative imports must include file extensions (e.g. `import './file.js'`) in native browser module configurations.