Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
How to use ES6 modules in CommonJS?

I've seen Importing ES6 modules in CommonJS Node app? How to use ES6 modules with commonjs and https://nodejs.org/api/esm.html#esm_enabling

And I still don't get it. Fairly new to javascript.

The fundamental question is "What do I need to do and where do the bits go that enable me to use ES6 modules inside CommonJS?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

In Node.js, if you want to import an ES module in a CommonJS module you can use dynamic import and the .mjs file extension on the ES modules. For example:

index.js CommonJS

const crypto = require('crypto');  // to show this is a commonJS module

import('./path/to/mod.mjs').then(mod =>
  console.log(mod.msg);    //  "Hello world!"
);

mod.mjs ES module

export const msg = "Hello world!";

Two examples of how import could be used within a CommonJS module to import all or some of the lodash-es package:

import('lodash-es').then(_ => {
  console.log(_.pad(_.toUpper('hello world'), 17, '*'));
});
Promise.all([
  import('lodash-es/pad.js'),
  import('lodash-es/toUpper.js'),
])
.then(([{ default: pad }, { default: toUpper }]) => {
  console.log(pad(toUpper('hello world'), 17, '#'));
});

Or you can just import what you need into a different CommonJS module then export a Promise which you can then import or require.

utils.js

module.exports = Promise.all([
  import('lodash-es/pad.js'),
  import('lodash-es/toUpper.js'),
]);

index.js

require('./utils.js').then(([{ default: pad }, { default: toUpper }]) => {
  console.log(pad(toUpper('hello world'), 17, '*'));
}); 
about 4 years ago · Juan Pablo Isaza Report

0

ESModules and CommonJS are mutually exclusive, so you can't "use ES6 modules inside CommonJS".

However, in a way, you can "use CommonJS inside ESModules", if by "CommonJS" you only mean the require() function. You can create an instance of require() function with module.createRequire():

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

// sibling-module.js is a CommonJS module.
const siblingModule = require('./sibling-module');

There's a chapter in NodeJS's documentation on interoperability between the two module systems. It's very helpful, you might want to check it out.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!