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

Problem 1: File Naming

The module need to be the exact name.

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

Problem 2: __dirname

After migration, the __dirname is not working anymore.

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

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



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store