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

NodeJS Jul 12, 2023

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.

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

Problem 2: __dirname

After migration, the __dirname is not working anymore.

Here are the alternative:

// 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

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

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

Here we go. Now we finish migrating.

Cheers !

Tags

TeamCMD

We are CODEMONDAY team and provide a variety of content about Business , technology, and Programming. Let's enjoy it with us.