You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<scriptsrc="add.umd.js"></script><script>// use imported function(s) as if they were declared globallyconsole.log(add(7,3));</script>
UMD under the hood
// IIFE(function(root,factory){// format will be commonjs, AMD (RequireJS) or a globalif(typeofexports==='object'&&typeofmodule!=='undefined'){module.exports=factory();}elseif(typeofdefine==='function'&&define.amd){define(factory);}else{root.myLibrary=factory();}// invoking IIFE}(this,function(){// Your module code will reside here}));
ES6 modules
Import
everything
import * as myModule from './modules/my-module.js';
destructuring
import {myExport} from './modules/my-module.js';
default
import myDef from "/src/a";
import myDef, { fn1, fn2 } from "/src/a"; = import default and others
Export
individual
export const log = inp => console.log(inp);
list
export { log, add as sum };
default
export default expression;
export { name1 as default, … };
Interoperability between both standards
in Node:
ES modules support became stable in version 15
"type": "module" in package.json to treat every module as a ESM module
for esm apps:
interoperability (for both default and named CJS exports) is very good, read more
configure you bundler to output 2 bundles, one esm and the other cjs (e.g. bundle.cjs.js & bundle.ems.js)
package.json config:
{
"type": "module",
// NOTE: because `type` = `module`, every file is treated as esm// to force a file be handled as commonjs, filename must've `.cjs` extension"main": "./dist/bundle.cjs", // "main" field defines the script that is used when the package directory is loaded via require()// use conditional exports within "exports" to define different package entry points per environment// including whether the package is referenced via require or via import"exports": {
"import": "./dist/bundle.js",
"require": "./dist/bundle.cjs"
}
}