Fix Cannot use import statement outside a module using Node And TypeScript

Clarck Monclair
2 min readAug 9, 2021

SyntaxError: Cannot use import statement outside a module.

Every developer who started diving deeper into node.js has already faced this error message. This can be very overwhelmed when you can't understand why it’s impossible to use import { MyModule } from "path/file/to/module".

To resolve this issue, you have to know how javascript works with node.js. Introducing the concept of commonjs, ESM, and so on. Let’s say in very quick words that all those versions of javascript can have different ways to import modules.

const { MyModule } = require('path/file/to/module') this is the way to import modules in commonjs.

import { MyModule } from "path/file/to/module".this is how you import modules in ESM.

Node.js is built on top of commonjs. You need to consider some parameters to be able to execute javascript in an ESM way. ESM is the standard JavaScript module system. Also called EcmaScript Module.

One of the solutions, if you are using typescript, is to export and import your modules in a commonjs way.

// mymodule.tsclass MyModule {
static greetings(){
console.log("Hello world!")
}
}
exports.module = MyModule

Somewhere else…

// main.tsconst MyModule = require("path/to/mymodule.ts") 
// the extension '.ts' is required otherwise you will get an error
MyModule.greeting() // Hello world!

Another solution is to compile your “.ts” files into a different repository and then execute the entry point compiled file. Let’s see a quick example:

// tsconfig.json can be something like
{
"compilerOptions":{
"target":"ESNEXT",
"module":"commonjs",
"outDir":"./build",
"rootDir":"./src" /* assuming that your code live in ./src */,
"moduleResolution":"node",
"baseUrl":".",
"esModuleInterop": true
}
}

Now you can easily export and import your module in this way:

// src/mymodule.tsclass MyModule {
static greetings(){
console.log("Hello world!")
}
}
export default MyModule

Somewhere else…

// src/main.ts
import MyModule from "path/to/mymodule"
MyModule.greeting() // Hello world!

Don’t forget to compile before executing your application. Your package.json can be something like:

// package.json
{
...
"scripts":{
"start":"npm run build && node ./build/main.js",
"build":"tsc "
}
...
}

I hope this quick story will help you have a better understanding of how node.js works.

Thank you for reading.

--

--