Hands-On: Bundle and Publish a Utility Library
🎯 Introduction
By the end of this article, you will have combined the previous five lessons to bundle a utility library ready for npm, including external dependencies, multiple output formats, and publishing configuration.
🧱 The Goal: Publish Your Utility Functions
Suppose we have written a utility library called my-utils with this source:
import { debounce } from 'lodash-es';
export function formatPrice(num) {
return '¥' + Number(num).toFixed(2);
}
export { debounce };
Our goals are:
- Produce both
esandcjsbuilds for different environments. - Provide an additional minified build.
- Configure
package.jsonso others can use the library after runningnpm install.
🛠 Step 1: Exclude Third-Party Dependencies with external
First, an important question: should lodash-es be included in the bundle?
No. When someone installs your library, npm installs lodash-es automatically. Including another copy in your bundle would duplicate the same code.
Use external to tell Rollup that these dependencies are provided separately and should not be bundled:
export default {
input: 'src/index.js',
external: ['lodash-es'],
output: {
file: 'dist/my-utils.esm.js',
format: 'es'
}
};
The output retains the external module reference:
export { debounce } from 'lodash-es';
function formatPrice(num) {
return '¥' + Number(num).toFixed(2);
}
export { formatPrice };
package.json under dependencies to external. Only your own source needs to be bundled.🛠 Step 2: Multiple Formats and a Minified Build
Combine the output formats and terser minification from earlier articles into the final configuration:
import resolve from '@rollup/plugin-node-resolve';
import terser from '@rollup/plugin-terser';
export default {
input: 'src/index.js',
external: ['lodash-es'],
output: [
{
file: 'dist/my-utils.esm.js',
format: 'es'
},
{
file: 'dist/my-utils.cjs.js',
format: 'cjs'
},
{
file: 'dist/my-utils.esm.min.js',
format: 'es',
plugins: [terser()]
}
],
plugins: [resolve()]
};
Run npm run build to generate three files:
| Output | Purpose |
|---|---|
my-utils.esm.js | For bundlers such as Vite / Webpack, with tree shaking support |
my-utils.cjs.js | For traditional Node.js environments |
my-utils.esm.min.js | Minified build with the smallest file size |
📦 Step 3: Configure package.json
With the bundles ready, you need to specify which file each environment should load. Configure three fields in package.json:
{
"name": "my-utils",
"version": "1.0.0",
"main": "dist/my-utils.cjs.js",
"module": "dist/my-utils.esm.js",
"files": ["dist"],
"scripts": {
"build": "rollup -c"
},
"dependencies": {
"lodash-es": "^4.17.21"
}
}
The three new fields mean:
main: The CommonJS entry point, loaded byrequire('my-utils').module: The ES module entry point, preferred by bundlers when importing the package, enabling tree shaking.files: Includes only thedistdirectory when publishing to npm, leaving out source and configuration files to reduce package size.
lodash-es in dependencies, rather than devDependencies. When consumers install your library, npm automatically installs the packages listed in dependencies.You can now run npm publish to publish the library. The NPM course covers the publishing process in detail.
💡 Review: A Standard Library Build Workflow
We can now put the steps together into a standard utility library workflow:
- Write the source as ES modules with explicit
import/exportdeclarations. - Add third-party dependencies to
externaland declare them independencies. - Generate
esandcjsbuilds, adding a minified build if needed. - Configure
main,module, andfilesinpackage.json. - Build with
npm run buildand publish withnpm publish.
These are the core steps behind the publishing workflows used by open-source libraries such as Vue and React.
❓ Questions and Answers
Q1: Can external be a function or a regular expression?
Yes. For many dependencies, use a regular expression such as external: [/^lodash/] to match package names starting with lodash. For a few dependencies, an array of strings is clearer.
Q2: Why not also provide a UMD build for browsers?
Loading libraries directly with <script> tags is less common now; most consumers use bundlers. If needed, add a umd output and configure its name as shown in the third article.
Q3: Do I need to publish the source code too?
Usually not. Publishing only the output with files: ["dist"] is enough. Some libraries include source files for debugging, but this is optional.
Q4: Must I run npm run build manually before every release?
Add "prepublishOnly": "npm run build" to package.json to build automatically when you run npm publish, preventing outdated output from being published.
🧪 Exercise
Turn rollup-demo into a publishable library:
- Export
formatPriceand re-exportdebouncefromlodash-esinsrc/index.js. - Configure
rollup.config.mjsas shown in this article to generate three outputs. - Complete the
main,module, andfilesfields inpackage.json.
{
"name": "my-utils",
"version": "1.0.0",
"main": "dist/my-utils.cjs.js",
"module": "dist/my-utils.esm.js"
// Add the files field here
}
🎉 You have learned Rollup's core skills! From your first bundle to a complete published utility library, you can now build JavaScript libraries independently. Try packaging your frequently used utility functions into a library and publishing it to npm!
