Hands-On: Bundle and Publish a Utility Library

Put your Rollup skills into practice with external dependencies, multiple output formats, and package.json publishing settings.

🎯 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:

src/index.js
import { debounce } from 'lodash-es';

export function formatPrice(num) {
    return '¥' + Number(num).toFixed(2);
}

export { debounce };

Our goals are:

  1. Produce both es and cjs builds for different environments.
  2. Provide an additional minified build.
  3. Configure package.json so others can use the library after running npm 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:

rollup.config.mjs
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:

dist/my-utils.esm.js
export { debounce } from 'lodash-es';

function formatPrice(num) {
    return '¥' + Number(num).toFixed(2);
}

export { formatPrice };
Add dependencies declared in 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:

rollup.config.mjs
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:

OutputPurpose
my-utils.esm.jsFor bundlers such as Vite / Webpack, with tree shaking support
my-utils.cjs.jsFor traditional Node.js environments
my-utils.esm.min.jsMinified 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:

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 by require('my-utils').
  • module: The ES module entry point, preferred by bundlers when importing the package, enabling tree shaking.
  • files: Includes only the dist directory when publishing to npm, leaving out source and configuration files to reduce package size.
Remember to put 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:

  1. Write the source as ES modules with explicit import / export declarations.
  2. Add third-party dependencies to external and declare them in dependencies.
  3. Generate es and cjs builds, adding a minified build if needed.
  4. Configure main, module, and files in package.json.
  5. Build with npm run build and publish with npm 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:

  1. Export formatPrice and re-export debounce from lodash-es in src/index.js.
  2. Configure rollup.config.mjs as shown in this article to generate three outputs.
  3. Complete the main, module, and files fields in package.json.
package.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!