Node.js : CommonJS to ES Module in 4 Steps without Transpiling or Babel Node

tanut aran
1 min readMar 25, 2021


With some adjustment we don’t need babel and transpiling.

Just Node.js. Up and running !

First of all, add type: module into your package.json

Here we go to fix the error.

Problem 1: File Naming

The module need to be the exact name.

It also makes sense to set this. Some reason behind this is that the module might guess wrong when you have .js and .ts in the same directory.

|_ a.js
|_ b.js
import a from 'a'
import a from 'a.js'

Problem 2: __dirname

After migration, the __dirname is not working anymore.

Here are the alternative:

readFileSync(path.join(__dirname, './data.proto'))
readFileSync(new URL('./data.proto', import.meta.url))

Problem 3: Incompatible CJS Named import

Sometimes, there are lib that’s not yet compatible with ‘Named import’

import sequelize from 'sequelize'
const { STRING, ARRAY } from sequelize

Problem 4: ReferenceError: require is not defined

Sometimes, there are the mixin style required

For example, winston-daily-rotate-file this one mutate the imported winston instance.

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
// working !

Here we go. Now we finish migrating.

Cheers !



tanut aran

Co-founder and Coder at work !