Created
August 1, 2020 17:28
-
-
Save bencmbrook/c473a00e47461f5cdbac09cd134dcfae to your computer and use it in GitHub Desktop.
Export shared code between Browser and Node (ESM/CJS dual export)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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