Fix “Cannot use import statement outside a module” in JavaScript
Contents
- In the browser
- Add type="module" to the script tag
- Things that change with modules
- In Node.js
- Option 1: "type": "module" in package.json
- Option 2: rename the file to .mjs
- Option 3: use require() instead
- After switching to ES modules
- In TypeScript
- Use tsx to run TypeScript files
- Or make tsconfig.json and package.json agree
- In Jest
- Transform the code, or use Vitest
- FAQ
You wrote import something from './file.js', ran it, and got this:
SyntaxError: Cannot use import statement outside a module
It means the file is being run as a classic script (in the browser) or as CommonJS (in Node.js), and neither of those understands import. The fix is to tell the runtime the file is an ES module. How you do that depends on where the code runs:
| Where | Fix |
|---|---|
| Browser | Add type="module" to the <script> tag |
| Node.js | Add "type": "module" to package.json, or rename the file to .mjs |
| TypeScript | Run it with tsx, or align module in tsconfig.json with your package.json |
| Jest | Transform with Babel or ts-jest, or switch to Vitest |
In the browser
Add type="module" to the script tag
A plain <script> is a classic script, where import isn’t allowed. type="module" turns it into a module.
<!-- Error -->
<script src="app.js"></script>
<!-- Works -->
<script type="module" src="app.js"></script>
Things that change with modules
- Import paths need the extension in the browser:
import { x } from './utils.js', not'./utils'. Only bundlers like Vite fill it in for you. - Modules don’t work from
file://. Openingindex.htmlby double-clicking it gives a CORS error instead. Serve the folder with any local server, likenpx serveor VS Code’s Live Server. - Modules are deferred automatically: they run after the HTML is parsed (one of the script loading tricks worth knowing), so you don’t need
DOMContentLoaded. - Top-level variables are private to the module. Functions you call from an inline
onclickmust be put onwindowexplicitly. Modules also run in strict mode, where a few extra reserved words like static and implements cannot be used as variable names.
# Serve the current folder at http://localhost:3000
npx serve .
In Node.js
Node.js treats .js files as CommonJS unless you tell it otherwise. Pick one of these.
Option 1: "type": "module" in package.json
The most common fix. Every .js file in the project becomes an ES module. If you don’t have a package.json yet, create one with npm init -y. Check that your npm packages support ES modules too: most do, but some older ones are CommonJS only.
{
"name": "my-app",
"type": "module"
}
Option 2: rename the file to .mjs
A .mjs file is always an ES module, whatever package.json says. Handy for a single script in a CommonJS project. (The opposite also exists: .cjs is always CommonJS.)
mv script.js script.mjs
node script.mjs
Option 3: use require() instead
If the project is CommonJS and you want to keep it that way, use require. For a package that only ships as an ES module, use a dynamic import(), which works in CommonJS too. Recent Node.js versions (22.12 and later) can also require() most ES modules directly. Not sure which version you have? Here’s how to check your Node version.
// CommonJS
const express = require('express');
// An ESM-only package from CommonJS
async function main() {
const { default: chalk } = await import('chalk');
console.log(chalk.blue('Hello'));
}
main();
After switching to ES modules
A few CommonJS features don’t exist in ES modules, so you may hit a new error next:
require is not defined: replacerequirewithimporteverywhere.__dirname is not defined: useimport.meta.dirname(Node.js 20.11+), or build it fromimport.meta.url.- Relative imports need the file extension:
'./db.js', not'./db'. - Importing JSON needs an import attribute:
import data from './data.json' with { type: 'json' }.
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const __dirname = import.meta.dirname
?? path.dirname(fileURLToPath(import.meta.url));
In TypeScript
Use tsx to run TypeScript files
ts-node is the usual source of this error: it compiles your imports according to tsconfig.json and can end up running ES module syntax as CommonJS. tsx runs TypeScript files directly and handles both module systems without configuration.
npm install --save-dev tsx
npx tsx src/index.ts
Or make tsconfig.json and package.json agree
If you compile with tsc, set module to NodeNext. TypeScript then emits ES modules or CommonJS based on the "type" field in package.json, so the output always matches what Node.js expects.
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "ES2022",
"outDir": "dist"
}
}
In Jest
Transform the code, or use Vitest
Jest runs tests as CommonJS by default. The simplest fixes are to let Babel (or ts-jest for TypeScript) convert the imports, or to switch to Vitest, which supports ES modules out of the box with an almost identical API. Another common cause: an ES-module-only package in node_modules, which Jest skips by default. Add it to transformIgnorePatterns.
// babel.config.cjs
module.exports = {
presets: [['@babel/preset-env', { targets: { node: 'current' } }]],
};
// jest.config.cjs: also transform an ESM-only package
module.exports = {
transformIgnorePatterns: ['/node_modules/(?!some-esm-package)'],
};
FAQ
What is the difference between ES modules and CommonJS?
They’re two module systems (more background in these JavaScript tips). CommonJS (require, module.exports) is Node.js’s original one. ES modules (import, export) are the JavaScript standard and work in browsers and Node.js. New projects should use ES modules.
Can I use import and require in the same file?
Not with static import in a CommonJS file. In an ES module you can create a require with createRequire(import.meta.url) from node:module, and in CommonJS you can use dynamic import().
Why does it work in my bundler but not in Node.js?
Bundlers like Vite and webpack understand import no matter how the file is configured, and convert it. Node.js runs the file as is, so it follows the "type" field and file extension.
Do I need type=”module” for every script?
Only for scripts that use import or export, or that are imported by one that does. A module can import other modules without them having their own script tags.
Related: JavaScript tips, use console.log like a pro and HTTP status codes.