How to fix Cannot import outside of module in React
This error occurs when import statements are used outside of valid ES module contexts, often caused by mismatched module systems (ESM vs CommonJS) or files not marked as modules. Fix by configuring your build tool or package.json to properly support ES modules.
Quick fix
Fixes SyntaxError
npm start # Should work with import statements- Verify your build tool is configured for ES modules
- For Node.js scripts, add 'type: module' to package.json
- If using Jest for testing, configure it to handle ES modules
- Fix TypeScript module configuration
npm start # Should work with import statementsCannot import outside of module
What this error means
This error occurs when JavaScript encounters an import statement outside of a valid ES module context. React applications use ES6 module syntax (import/export), but they must run in an environment that understands modules. The error typically happens when your build system, Node.js runtime, or browser doesn't recognize the file as a module, or when trying to import in a CommonJS context.
Typical symptoms
- Import statements cause syntax errors during build or runtime
- Error appears when running scripts with Node.js or in Jest tests
- Working in browser but fails when running server-side code
- Mixed usage of import and require statements in same project
- Third-party dependencies fail to load with import syntax
Common causes
- Missing 'type': 'module' declaration in package.json for Node.js projects
- Using CommonJS (require) configuration while trying to use ES6 imports
- Test runner like Jest not configured to handle ES modules
- Build tool (webpack, Vite, etc.) not transpiling import statements
- Files missing .mjs extension when explicitly needed for ES modules
- TypeScript tsconfig.json module setting incompatible with import syntax
- Script tag missing type='module' attribute in HTML
How to fix "Cannot import outside of module"
If using Create React App, Vite, or Next.js, these already support ES modules by default. Check your build configuration:
For Create React App:
npm start # Should work with import statementsFor Vite (modern React projects):
// vite.config.js already supports ESM
export default {
// Configuration here
}For Next.js:
// import statements work by default in pages and components
import React from 'react';If running Node.js scripts directly (not in a browser), add the module type:
{
"name": "my-app",
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "node index.js"
}
}Or rename your file to use .mjs extension:
mv index.js index.mjs
node index.mjs # Now import statements workUpdate your Jest configuration to transform imports:
// jest.config.js
export default {
transform: {
'^.+\\.jsx?$': 'babel-jest',
},
testEnvironment: 'jsdom',
};Or use Node with experimental ESM support:
node --experimental-vm-modules node_modules/jest/bin/jest.jsIf using TypeScript, update tsconfig.json to use modern module system:
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2020", "DOM"]
}
}If importing in an HTML file, mark scripts as modules:
<!-- Correctly marks file as module -->
<script type="module" src="app.js"></script>
<!-- In app.js, imports now work -->
import React from 'react';
import { useState } from 'react';Don't mix import and require in the same project:
// ❌ Bad: mixing both styles
const React = require('react'); // CommonJS
import { useState } from 'react'; // ES Module
// ✅ Good: use consistent style
import React from 'react';
import { useState } from 'react';If a dependency only supports CommonJS, use dynamic imports:
// ✅ Works in ES modules
const myModule = await import('commonjs-module');Advanced notes
JavaScript has two module systems. CommonJS (require/module.exports) was designed for server-side Node.js and uses synchronous loading. ES Modules (import/export) are the modern standard, used in browsers and modern Node.js, and support both synchronous and asynchronous loading.
In ES modules, you can use await at the top level of a file without wrapping in an async function. This is not possible in CommonJS.
Modern bundlers automatically detect your module system. Create React App, Next.js, and Vite all handle this configuration automatically, so this error is rare when using these tools. It's more common when writing Node.js scripts or configuring build tools manually.
Frequently asked questions
- What does "SyntaxError" mean?
- This error occurs when JavaScript encounters an import statement outside of a valid ES module context. React applications use ES6 module syntax (import/export), but they must run in an environment that understands modules. js runtime, or browser doesn't recognize the file as a module, or when trying to import in a CommonJS context.
- How do I fix "SyntaxError"?
- This error occurs when import statements are used outside of valid ES module contexts, often caused by mismatched module systems (ESM vs CommonJS) or files not marked as modules. Fix by configuring your build tool or package.json to properly support ES modules.
- What causes "SyntaxError"?
- Missing 'type': 'module' declaration in package.json for Node.js projects Using CommonJS (require) configuration while trying to use ES6 imports Test runner like Jest not configured to handle ES modules
- Is the "SyntaxError" error serious?
- It is a medium-severity error — more of a blocker than a risk. The steps above resolve it.