Work with our skilled Node developers to accelerate your project and boost its performance.
Hire Node.js DevelopersWhen using TypeScript or JavaScript with ES Modules (import/export syntax), you might encounter the following error:
SyntaxError: Cannot use import statement outside a module
This happens when Node.js or the TypeScript compiler does not recognize your file as an ES Module.
For Node.js to recognize ES Module syntax, update your package.json file:
{ "type": "module" }
If your project uses CommonJS (require() syntax), remove “type”: “module” or use dynamic imports instead.
TypeScript recognizes .mts files as ES Modules. If you’re using JavaScript, rename .js to .mjs.
Example:
myfile.ts → myfile.mts
Ensure your TypeScript configuration supports ES Modules by updating tsconfig.json:
{ "compilerOptions": { "module": "ESNext", "moduleResolution": "node" } }
Then, recompile your TypeScript files:
tsc
If you’re dynamically importing a module, use import():
(async () => { const module = await import('./myModule.js'); console.log(module.default); })();
If you’re running your script with Node.js, use:
node --loader ts-node/esm myfile.ts
or for JavaScript:
node --experimental-modules myfile.mjs
By following these steps, you can resolve the “Cannot use import statement outside a module” error in TypeScript.