Skip to content

Instantly share code, notes, and snippets.

@bencmbrook
Created August 1, 2020 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bencmbrook/c473a00e47461f5cdbac09cd134dcfae to your computer and use it in GitHub Desktop.
Save bencmbrook/c473a00e47461f5cdbac09cd134dcfae to your computer and use it in GitHub Desktop.
Export shared code between Browser and Node (ESM/CJS dual export)
/* Export a file to be imported by both Node and Browser.
*
* module.exports = sharedFunction;
* AND
* export default sharedFunction;
*/
// shared-code.js
function sharedFunction(x) {
return x * 2;
}
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.default = sharedFunction;
/*** Importing in Node (CommonJS) ***/
const sharedFunction = require('shared-code.js').default;
/*** Importing in the Browser (ES Modules) ***/
import sharedFunction from './shared-code.js';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment