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.

directory
|_ a.js
|_ b.js
import a from 'a'
// NOT WOKRING
import a from 'a.js'
// WOKRING

Problem 2: __dirname

After migration, the __dirname is not working anymore.

// BEFORE
readFileSync(path.join(__dirname, './data.proto'))
// AFTER
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);
require('...')
// 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