Key points
- The error means a file that uses
importis being run as a classic script or as CommonJS, not as an ES module. - In the browser, add
type="module"to the script tag; in Node.js, set"type": "module"in package.json or use the.mjsextension. - Fixing it often uncovers the next errors: no
requireor__dirname, paths without extensions, functions that are no longer global.
You split your JavaScript into several files, write your first import, and the console shows “Uncaught SyntaxError: Cannot use import statement outside a module”. It’s one of the most common JavaScript errors because it sits right on the border between two module systems that still live side by side: ES modules (import/export), the language standard, and CommonJS (require/module.exports), Node.js’s original system. The message reads the same in the browser and in Node, but the fix is different. Here’s how to pin it down in seconds, fix it properly in each environment, and avoid the chain of errors that tends to follow the first fix.
What the message is really telling you
A JavaScript file can be interpreted in two ways: as a classic script (or a CommonJS module in Node), or as an ES module. The import keyword only exists in the second case. The engine doesn’t infer the type from the file’s contents; it goes by how the file was loaded. If nothing says it’s a module, it reads the file as a script, hits import on line one and stops with a syntax error.
So the message isn’t pointing at a bug in your code but at how the file is declared. The first question is: where does this code run? In a browser, the fix goes in the HTML. In Node.js, in package.json or the file extension. In a test runner or bundler, in its configuration.
The mirror-image message exists too, with the same root cause: “require is not defined in ES module scope” means the file is treated as an ES module while using CommonJS syntax.
In the browser: type=”module” and what it changes
In the browser, the fix is a single attribute:
<!-- Triggers the error: the file is loaded as a classic script -->
<script src="/js/app.js"></script>
<!-- Correct: the browser loads it as an ES module -->
<script type="module" src="/js/app.js"></script>
Only the entry point needs the attribute: files imported from a module are modules automatically. But the switch changes several behaviours, and that’s where the next errors come from:
- Paths must be explicit.
import { x } from 'utils'fails with “Failed to resolve module specifier”: the browser expects a path starting with/,./or../, including the.jsextension. Bare package names only work with a bundler or an import map. - Variables are no longer global. A function declared in a module can’t be reached from an inline
onclick="myFunction()": you get “myFunction is not defined”. Attach events withaddEventListenerinside the module. - Execution is deferred. A module runs like a
deferscript, after the HTML has been parsed. That’s usually what you want, but a classic script that relies on a module loaded further down may now run before it. - No modules over
file://. Opening the page by double-clicking the HTML file triggers a CORS error: modules must be served over HTTP, even locally (npx serve, your editor’s live server extension or your project’s dev server).
// /js/app.js
import { formatPrice } from './utils/price.js'; // relative path AND extension
import { openCart } from './cart.js';
document.querySelector('#cart')
.addEventListener('click', openCart); // instead of onclick="..." in the HTML
console.log(formatPrice(1290));
Strict mode is also on by default in a module. Old code that assigns to an undeclared variable now throws instead of silently creating a global: that’s a bug being revealed, not introduced.
In Node.js: package.json, .mjs and mixing with CommonJS
Node.js treats a .js file as CommonJS unless told otherwise. You have three options:
- switch the whole project to ES modules with
"type": "module"inpackage.json; - rename just that file to
.mjs(and conversely,.cjsforces CommonJS inside an ESM project); - stay on CommonJS and replace
importwithrequire().
{
"name": "export-tool",
"version": "1.0.0",
"type": "module",
"scripts": {
"export": "node src/export.js"
}
}
On our recent projects we start with ES modules: it’s the standard, and more and more packages are only published that way. But switching an existing project to "type": "module" surfaces new errors, because several CommonJS conveniences disappear:
// In CommonJS, __dirname was always there. In an ES module:
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { createRequire } from 'node:module';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// (on recent Node versions: import.meta.dirname)
// Load a CommonJS module or a JSON file "the old way" if needed
const require = createRequire(import.meta.url);
const config = require('./config.json');
const templates = path.join(__dirname, 'templates');
Other things to check during the switch: relative imports need the extension (./db.js, not ./db), tool config files that use module.exports must be renamed to .cjs, and any require called inside a function has to become a top-level import or a dynamic import().
The reverse case is common as well: a CommonJS project upgrades a package that has gone ESM-only, and ERR_REQUIRE_ESM appears. Recent Node versions can require() an ES module as long as it doesn’t use top-level await; on older versions, a dynamic import works from a CommonJS file:
// CommonJS file that needs a package published as ESM only
async function send() {
const { default: pLimit } = await import('p-limit');
const limit = pLimit(3);
// ...
}
In WordPress, test runners and build tools
In a WordPress theme or plugin, wp_enqueue_script() outputs a classic script. If your file uses import, you get exactly this error. Since WordPress 6.5, a dedicated function prints the right tag:
<?php
// WordPress 6.5 and later: register a real ES module
add_action( 'wp_enqueue_scripts', function () {
wp_enqueue_script_module(
'agency-map',
get_stylesheet_directory_uri() . '/js/map.js',
[],
'1.0.0'
);
} );
Be aware that a module registered this way can’t be listed as a dependency of a classic script, and data passed with wp_localize_script() doesn’t reach it. To pass values (API URL, nonce), put them in a data- attribute in the markup or in a global object set by a classic script loaded beforehand. On older versions, adding type="module" through the script_loader_tag filter gets you by, but it’s a workaround.
If you use a build tool (Vite, webpack, @wordpress/scripts), it turns your imports into compatible bundles, and the error only shows up if you accidentally load the source file instead of the built one. That’s a classic cause after a deployment: check the tag points at the output folder (build/ or dist/).
Finally, test runners have their own configuration. Jest, originally designed around CommonJS, throws this error when it meets untransformed ESM code, typically a package in node_modules published as ESM. Depending on the project, you configure those packages to be transformed, enable Jest’s ESM support, or move to a natively ESM runner such as Vitest. On our recent front-end projects, that last option is the one we pick most often.
FAQ
Do I have to choose between import and require in one project?
Yes, at least per file: a file is either an ES module or CommonJS. A project can contain both (.mjs and .cjs), but consistency avoids most of these errors. For a new project, ES modules are the more future-proof choice.
Why does the error appear in production but not locally?
Usually because the dev server transforms code on the fly, while in production the page loads a source file instead of the built one, or a tag without type="module". Compare the generated script tags in both environments.
Can adding type=”module” break existing code?
Yes: variables stop being global, strict mode applies and execution is deferred. Test any inline onclick handlers and scripts that depend on functions defined in that file.
A JavaScript error blocking your site or app, or a codebase to modernise without breaking everything? We diagnose, fix and restructure the front-end and Node.js code behind your projects.



