Suppose you've written a small library that exposes a summation function, sum([2, 3]), and internally uses an addition function from another file. Before publishing, you want people to be able to install the library. You also want someone to be able to load it on a webpage with one <script> tag. Both steps often get called “packaging.” Looking at who will receive the result helps explain the division of labor.
What do Rollup and npm pack each produce?
| Desired result | Tool | What you see when you open it |
|---|---|---|
| A script for a webpage to load | Rollup starts at the entry point, follows import statements to the modules in use, and writes the requested output format. | A JavaScript file that includes the addition function. In this example, the page loads just one script.1 |
| An npm package others can install | Run npm pack in the project directory containing package.json. | A compressed .tgz archive. Extract it to see package.json with the name and version, plus the code and documentation distributed with the package.2 |
If your library already consists of one directly runnable JS file, you can put it straight into an npm package. For libraries with a build step, you usually run npm run build first. It executes the command the author put in scripts.build in package.json. If that's rollup -c, Rollup reads the configuration and writes the results to the specified location. A common output directory is dist. Next, npm pack --dry-run lets you inspect the file list and confirm the generated files are included before actually creating the archive.2
Where do the types go when TypeScript becomes JS?
In the addition function, a parameter written a: number tells the caller to pass a number. TypeScript's compiler, tsc, checks the types. When generating JavaScript, it removes the : number annotations from the parameters and return value, leaving the runnable function. Turn on declaration and you also get a declaration file, .d.ts. Inside, export declare function add(a: number, b: number): number; tells the editor how to call the function. A reader typing add("1", 2) can see that a string can't be passed to a numeric parameter, while the code that does the addition remains in the JS file.3
If the library exports a React component, its declaration may refer to React's own types. When my application read a Context exposed by a local component package, I ran into a mismatch between two definitions of ReactNode. Why does useContext report that bigint can't be assigned to ReactNode?
When do Rollup plugins, Gulp tasks, and middleware run?
A Rollup plugin adds an operation to the build. Rollup calls functions provided by plugins while resolving dependencies, reading files, transforming source, and generating output. These designated call sites are hooks. For example, a plugin can receive a module's source in its transform hook and convert its TypeScript into JavaScript that Rollup can continue processing.4
Gulp schedules tasks. Suppose a release needs to clear dist, then build scripts and copy icons concurrently. In Gulp, that can be series(clean, parallel(buildJs, copyIcons)). You define those three tasks, and buildJs can call Rollup. When you see .pipe(...) in a Gulp task, think “pass the files processed in this step to the next step.”5
Middleware can also process inputs step by step. In Express, middleware runs when a server receives an HTTP request. Logging middleware might read the request URL and call next() to pass the request downstream. A Rollup plugin might receive source code awaiting transformation, while the logging middleware receives an incoming request.6
Configuration example: package a TypeScript sum function as an installable npm library
The goal is small: have the same sum([2, 3]) return 5 in a project using import, one using require(), and an ordinary webpage. Create an empty directory called sum-demo and save the code under the filenames below. This example uses Node.js 22.
1. Write the function other people will call
src/math.ts contains an addition function:
export function add(a: number, b: number): number {
return a + b;
}
src/index.ts is the library entry point. Callers only need to know the name sum. Starting at zero, reduce adds each number in the array to the running total.
import { add } from "./math.js";
export function sum(values: number[]): number {
return values.reduce(add, 0);
}
The import uses ./math.js because that's the compiled filename. TypeScript can resolve that path to math.ts when checking the source.
2. Have TypeScript check the types and generate JS
tsconfig.json tells tsc where to find the source and where to write the output. After this step, .build/index.js still imports math.js, while .build/index.d.ts contains just the public declaration: export declare function sum(values: number[]): number;. In the next step Rollup follows the import and combines the two JavaScript modules.3
{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"rootDir": "src",
"outDir": ".build",
"strict": true,
"noEmitOnError": true,
"declaration": true
},
"include": ["src"]
}
3. Tell npm how to build and where to load the installed library
The build script in package.json runs TypeScript first and Rollup second. The prepack script lets npm pack build automatically before packing. The files field limits distributed code to dist, and npm includes package.json itself.27
{
"name": "sum-demo",
"version": "1.0.0",
"type": "module",
"files": ["dist"],
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
},
"scripts": {
"build": "tsc && rollup -c",
"prepack": "npm run build"
},
"devDependencies": {
"@rollup/plugin-terser": "0.4.4",
"rollup": "4.40.2",
"rollup-plugin-gzip": "4.0.1",
"typescript": "5.8.3"
}
}
To read exports, start with what the caller writes. import { sum } from "sum-demo" follows the import branch, and require("sum-demo") follows the require branch. Each branch lists two files: TypeScript reads types to check usage, and Node.js reads default to execute the code.8
With only one entry point, you can put the type declaration directly in the top-level types field of package.json. To see how an editor jumps from a declaration back to local source after importing by package name, see Testing a TypeScript package from two directories.
4. Have Rollup generate three entry points, compressing only the web version
In rollup.config.mjs, input is the JS file just compiled. Each item in the output array specifies an output. The first two produce files for projects to import. The last creates a UMD script that an ordinary webpage can call through the global name SumDemo.9
import { readFileSync } from "node:fs";
import terser from "@rollup/plugin-terser";
import gzip from "rollup-plugin-gzip";
function includeTypes(fileName) {
return {
name: "include-types",
generateBundle() {
const source = readFileSync(".build/index.d.ts", "utf8");
this.emitFile({ type: "asset", fileName, source });
}
};
}
export default {
input: ".build/index.js",
output: [
{
file: "dist/index.mjs",
format: "es",
plugins: [includeTypes("index.d.mts")]
},
{
file: "dist/index.cjs",
format: "cjs",
plugins: [includeTypes("index.d.cts")]
},
{
file: "dist/sum.min.js",
format: "umd",
name: "SumDemo",
plugins: [terser(), gzip()]
}
]
};
Here you can see a complete small plugin. During output generation, Rollup calls the generateBundle hook on includeTypes, which uses this.emitFile to add declarations to the output. This example's declaration uses only number, and both entry points export the same named function. They can share the declaration contents and use .d.mts and .d.cts to mark the respective module formats.48
The web output uses two existing plugins. terser() shortens the JS into a still-executable sum.min.js, then gzip() generates sum.min.js.gz. The HTML still references the .js file. Only if the server is configured to serve precompressed assets will it send the .gz according to the browser's supported encodings. That file holds just one script, while npm's .tgz contains the whole library.10
5. Install the archive in another project and try it
In the sum-demo directory, run:
npm install
npm pack --dry-run
npm pack
In the preview you should see three JS entry points, two declaration files, and one .gz file. The last command produces sum-demo-1.0.0.tgz. Create a sibling directory for the consumer and install the file you just generated:
mkdir ../try-sum
cd ../try-sum
npm init -y
npm install ../sum-demo/sum-demo-1.0.0.tgz
node --input-type=module -e "import { sum } from 'sum-demo'; console.log(sum([2, 3]))"
node -e "const { sum } = require('sum-demo'); console.log(sum([2, 3]))"
Both Node commands should print 5. Save the following lines as try-sum/index.html and open it in your browser. The page should display 5 as well. The name SumDemo comes from the Rollup configuration's name option.
<!doctype html>
<meta charset="utf-8">
<output id="result"></output>
<script src="./node_modules/sum-demo/dist/sum.min.js"></script>
<script>
document.getElementById("result").textContent = SumDemo.sum([2, 3]);
</script>
Footnotes
-
Rollup. (n.d.). Introduction, “Overview”. Rollup Documentation. https://rollupjs.org/introduction/#overview ↩
-
npm. (n.d.). npm pack, “Description” and “dry-run”. npm Docs. https://docs.npmjs.com/cli/v11/commands/npm-pack/#description ↩ ↩2 ↩3
-
Microsoft. (n.d.). The basics, “Erased types”. TypeScript Handbook. https://www.typescriptlang.org/docs/handbook/2/basic-types.html#erased-types;Microsoft. (n.d.). declaration. TSConfig Reference. https://www.typescriptlang.org/tsconfig/declaration.html ↩ ↩2
-
Rollup. (n.d.). Plugin development, “Build hooks” and “transform”. Rollup Documentation. https://rollupjs.org/plugin-development/#transform ↩ ↩2
-
Gulp. (n.d.). Creating tasks, “Compose tasks”. Gulp Documentation. https://gulpjs.com/docs/en/getting-started/creating-tasks/#compose-tasks;Gulp. (n.d.). Working with files. Gulp Documentation. https://gulpjs.com/docs/en/getting-started/working-with-files/ ↩
-
Express. (n.d.). Using middleware. Express Guide. https://expressjs.com/en/guide/using-middleware/ ↩
-
npm. (n.d.). Scripts, “npm pack”. npm Docs. https://docs.npmjs.com/cli/v11/using-npm/scripts/#npm-pack ↩
-
Microsoft. (2022). TypeScript 4.7, “package.json exports, imports, and self-referencing”. TypeScript Documentation. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-7.html#packagejson-exports-imports-and-self-referencing ↩ ↩2
-
Rollup. (n.d.). Configuration options, “output.format” and “output.plugins”. Rollup Documentation. https://rollupjs.org/configuration-options/#output-format ↩
-
Rollup. (n.d.). @rollup/plugin-terser. GitHub. https://github.com/rollup/plugins/tree/master/packages/terser#usage;Manzinger, M. (n.d.). rollup-plugin-gzip. GitHub. https://github.com/kryops/rollup-plugin-gzip#readme ↩