Facebook Pixel

Can I import CommonJS modules in ES modules in Node.js?

Yes. The module.exports of a CommonJS module becomes the default import in an ES module. For example, 'import express from "express"' works because express uses module.exports.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in How to Use ES Modules in Node.js: A Practical Guide

Set 'type': 'module' in your package.json to make all .js files ES modules, or use the .mjs file extension for individual files. This tells Node.js to treat your files as ES modules instead of CommonJS.

Use export to share values: 'export function add() {}' or 'export const x = 1'. Use import to use them: 'import { add } from "./utils.js"'. The .js extension is required in Node.js ES modules, unlike bundlers that infer it.

The ability to use await at the top level of an ES module without wrapping in an async function. This is a real advantage over CommonJS for startup async work like connecting to a database before the server starts.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.