Using ES modules with CommonJS modules with webpack

  1. The three differences between require and import in Node.js
  2. Using ES modules with CommonJS modules in Node.js
  3. Using ES modules with CommonJS modules in the browser
  4. Using ES modules with CommonJS modules with webpack

Webpack modules

javascript_modules/browser $ python3 -m http.server 1234
// index.jsimport { myEsModuleExportedFunction } from "./es_module.js";
const { myCommonJsModuleExportedFunction } = require("./commonjs_module.js");
// do some stuff...

Mixing module methods

  • ES module statements (import and export)
  • CommonJS require statements
  • AMD define and require statements
  • and more… (see the full list here)
Not too complicated

A couple more things to note

console.log("export_both");exports.exportBothCommonJs = function () {
return "lion";
};
// If you want to use exports, this needs to be commented out.
// export function exportBothEs() {
// return "tiger";
// }

Resources

--

--

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