This document explains the UMD (Universal Module Definition) build configuration for SquibView, which ensures proper compatibility across different JavaScript environments.
UMD is a module pattern that aims to be compatible with the most popular script loaders (and if no module loader is found, it registers itself as a global variable).
The UMD build should work in all these contexts:
The key parts of our UMD configuration:
{
input: 'src/squibview.js',
output: {
file: 'dist/squibview.umd.js',
format: 'umd',
name: 'SquibView',
sourcemap: true,
inlineDynamicImports: true,
// Explicitly export the default export as the main exportexports: 'auto',
// Override the generated UMD wrapper slightly to ensure it works in browsersbanner: '/* SquibView UMD build */',
footer: '/* Make SquibView directly available as a global */\ntypeof window !== "undefined" && (window.SquibView = typeof SquibView.default === "function" ? SquibView.default : SquibView);'
},
plugins: [
resolve({
extensions,
browser: true, // Ensure browser-compatible modules are usedpreferBuiltins: false
}),
commonjs({
// Better CommonJS conversiontransformMixedEsModules: true,
// Ensure default exports are properly handlednamedExports: {
'tiny-emitter': ['TinyEmitter'],
'diff-match-patch': ['diff_match_patch']
}
}),
babel({
extensions,
exclude: 'node_modules/**',
babelHelpers: 'bundled',
presets: ['@babel/preset-env'],
plugins: [
'@babel/plugin-transform-modules-umd'
]
}),
],
}
format: 'umd'
- Specifies the UMD format.name: 'SquibView'
- The global variable name to use when no module system is found.exports: 'auto'
- Automatically determines the export mode based on the input.footer
- A small piece of code that ensures the class is properly assigned to window.SquibView
in browser environments, handling both default and named exports.resolve({browser: true})
- Ensures browser-compatible versions of dependencies are used.commonjs({namedExports})
- Properly handles CommonJS dependencies, explicitly specifying exports for libraries that don’t follow standard patterns.babel({plugins})
- Uses Babel to transform ES6+ code to be compatible with older environments, with specific plugins to handle UMD transformations.ES modules use export default
syntax, which can cause issues in UMD builds. When bundling ES modules as UMD, the default export sometimes gets wrapped in an object with {default: actualExport}
. Our configuration ensures:
To verify the UMD build:
Test as a direct script tag:
<scriptsrc="../dist/squibview.umd.min.js"></script><script>const editor = newSquibView('#editor');
</script>
Check that window.SquibView
is properly defined by inspecting the console:
console.log(typeofSquibView); // Should print "function"console.log(SquibView.version); // Should access version properly
If the UMD build doesn’t work properly:
dist/squibview.umd.js
file to verify exports are handled correctly