• Stars
    star
    249
  • Rank 162,987 (Top 4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 2 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

📦 🍣 Next-gen package bundler for TypeScript & ESM

📦 🍣 pkgroll

Pkgroll is a next-gen package bundler that infers how to build your package from entry-points defined in package.json. No configuration necessary!

Write your code in TypeScript/ESM and run pkgroll to get ESM/CommonJS/DTS outputs!

Found this package useful? Show your support & appreciation by sponsoring! ❤️

Install

npm install --save-dev pkgroll

Quick setup

  1. Setup your project with source files in src and output in dist (configurable).

  2. Define package entry-files in package.json.

    These configurations are for Node.js to determine how to import the package.

    Pkgroll leverages the same configuration to determine how to build the package.

    {
        "name": "my-package",
    
        // Set "module" or "commonjs" (https://nodejs.org/api/packages.html#type)
        // "type": "module",
    
        // Define the output files
        "main": "./dist/index.cjs",
        "module": "./dist/index.mjs",
        "types": "./dist/index.d.cts",
    
        // Define output files for Node.js export maps (https://nodejs.org/api/packages.html#exports)
        "exports": {
            "require": {
                "types": "./dist/index.d.cts",
                "default": "./dist/index.cjs"
            },
            "import": {
                "types": "./dist/index.d.mts",
                "default": "./dist/index.mjs"
            }
        },
    
        // bin files will be compiled to be executable with the Node.js hashbang
        "bin": "./dist/cli.js",
    
        // (Optional) Add a build script referencing `pkgroll`
        "scripts": {
            "build": "pkgroll"
        }
    
        // ...
    }

    Paths that start with ./dist/ are automatically mapped to files in the ./src/ directory.

  3. Package roll!

    npm run build # or npx pkgroll

Usage

Entry-points

Pkgroll parses package entry-points from package.json by reading properties main, module, types, and exports.

The paths in ./dist are mapped to paths in ./src (configurable with --src and --dist flags) to determine bundle entry-points.

Output formats

Pkgroll detects the format for each entry-point based on the file extension or the package.json property it's placed in, using the same lookup logic as Node.js.

package.json property Output format
main Auto-detect
module ESM
Note: This unofficial property is not supported by Node.js and is mainly used by bundlers.
types TypeScript declaration
exports Auto-detect
exports.require CommonJS
exports.import Auto-detect
exports.types TypeScript declaration
bin Auto-detect
Also patched to be executable with the Node.js hashbang.

Auto-detect infers the type by extension or package.json#type:

Extension Output format
.cjs CommonJS
.mjs ECMAScript Modules
.js Determined by package.json#type, defaulting to CommonJS

Dependency bundling & externalization

Packages to externalize are detected by reading dependency types in package.json. Only dependencies listed in devDependencies are bundled in.

When generating type declarations (.d.ts files), this also bundles and tree-shakes type dependencies declared in devDependencies as well.

// package.json
{
    // ...

    "peerDependencies": {
        // Externalized
    },
    "dependencies": {
        // Externalized
    },
    "optionalDependencies": {
        // Externalized
    },
    "devDependencies": {
        // Bundled
    },
}

Aliases

Aliases can be configured in the import map, defined in package.json#imports.

For native Node.js import mapping, all entries must be prefixed with # to indicate an internal subpath import. Pkgroll takes advantage of this behavior to define entries that are not prefixed with # as an alias.

Native Node.js import mapping supports conditional imports (eg. resolving different paths for Node.js and browser), but Pkgroll does not.

⚠️ Aliases are not supported in type declaration generation. If you need type support, do not use aliases.

{
    // ...

    "imports": {
        // Mapping '~utils' to './src/utils'
        "~utils": "./src/utils",

        // Native Node.js import mapping (can't reference ./src)
        "#internal-package": "./vendors/package/index.js",
    }
}

Target

Pkgroll uses esbuild to handle TypeScript and JavaScript transformation and minification.

The target specifies the environments the output should support. Depending on how new the target is, it can generate less code using newer syntax. Read more about it in the esbuild docs.

By default, the target is set to the version of Node.js used. It can be overwritten with the --target flag:

pkgroll --target=es2020 --target=node14.18.0

It will also automatically detect and include the target specified in tsconfig.json#compilerOptions.

Strip node: protocol

Node.js builtin modules can be prefixed with the node: protocol for explicitness:

import fs from 'node:fs/promises'

This is a new feature and may not work in older versions of Node.js. While you can opt out of using it, your dependencies may still be using it (example package using node:: path-exists).

Pass in a Node.js target that that doesn't support it to strip the node: protocol from imports:

pkgroll --target=node12.19

Export condition

Similarly to the target, the export condition specifies which fields to read from when evaluating export and import maps.

For example, to simulate import resolutions in Node.js, pass in node as the export condition:

pkgroll --export-condition=node

ESM ⇄ CJS interoperability

Node.js ESM offers interoperability with CommonJS via static analysis. However, not all bundlers compile ESM to CJS syntax in a way that is statically analyzable.

Because pkgroll uses Rollup, it's able to produce CJS modules that are minimal and interoperable with Node.js ESM.

This means you can technically output in CommonJS to get ESM and CommonJS support.

require() in ESM

Sometimes it's useful to use require() or require.resolve() in ESM. ESM code that uses require() can be seamlessly compiled to CommonJS, but when compiling to ESM, Node.js will error because require doesn't exist in the module scope.

When compiling to ESM, Pkgroll detects require() usages and shims it with createRequire(import.meta.url).

Environment variables

Pass in compile-time environment variables with the --env flag.

This will replace all instances of process.env.NODE_ENV with 'production' and remove unused code:

pkgroll --env.NODE_ENV=production

Minification

Pass in the --minify flag to minify assets.

pkgroll --minify

Watch mode

Run the bundler in watch mode during development:

pkgroll --watch

FAQ

Why bundle with Rollup?

Rollup has the best tree-shaking performance, outputs simpler code, and produces seamless CommonJS and ESM formats (minimal interop code). Notably, CJS outputs generated by Rollup supports named exports so it can be parsed by Node.js ESM. TypeScript & minification transformations are handled by esbuild for speed.

Why bundle Node.js packages?

  • ESM and CommonJS outputs

    As the Node.js ecosystem migrates to ESM, there will be both ESM and CommonJS users. A bundler helps accommodate both distribution types.

  • Dependency bundling yields smaller and faster installation.

    Tree-shaking only pulls in used code from dependencies, preventing unused code and unnecessary files (eg. README.md, package.json, etc.) from getting downloaded.

    Removing dependencies also eliminates dependency tree traversal, which is one of the biggest bottlenecks.

  • Inadvertent breaking changes

    Dependencies can introduce breaking changes due to a discrepancy in environment support criteria, by accident, or in rare circumstances, maliciously.

    Compiling dependencies will make sure new syntax & features are downgraded to support the same environments. And also prevent any unexpected changes from sneaking in during installation.

  • Type dependencies must be declared in the dependencies object in package.json, instead of devDependencies, to be resolved by the consumer.

    This may seem counterintuitive because types are a development enhancement. By bundling them in with your package, you remove the need for an external type dependency. Additionally, bundling only keeps the types that are actually used which helps minimize unnecessary bloat.

  • Minification strips dead-code, comments, white-space, and shortens variable names.

Sponsors

More Repositories

1

tasuku

✅ タスク — The minimal task runner for Node.js
TypeScript
1,687
star
2

minification-benchmarks

🏃‍♂️🏃‍♀️🏃 JS minification benchmarks: babel-minify, esbuild, terser, uglify-js, swc, google closure compiler, tdewolff/minify
TypeScript
830
star
3

cleye

👁‍🗨 cleye — The intuitive & typed CLI development tool for Node.js
TypeScript
361
star
4

snap-tweet

Snap a screenshot of a tweet 📸
TypeScript
312
star
5

vue-2-3

↔️ Interop Vue 2 components in Vue 3 apps and vice versa
JavaScript
277
star
6

ts-runtime-comparison

Comparison of Node.js TypeScript runtimes
TypeScript
219
star
7

vue-frag

🤲 Create Fragments (multiple root-elements) in Vue 2
TypeScript
194
star
8

link

🔗 A better `npm link`
TypeScript
117
star
9

type-flag

⛳️ Typed command-line arguments parser for Node.js
TypeScript
114
star
10

get-tsconfig

tsconfig.json paser & paths matcher
TypeScript
91
star
11

github-cdn

🛰 Github CDN Server
JavaScript
47
star
12

ci

Run npm ci using the appropriate Node package manager (npm, yarn, pnpm)
TypeScript
45
star
13

dbgr

Lightweight debugger for Node.js
TypeScript
44
star
14

clean-pkg-json

Script to remove unnecessary properties from package.json on prepublish hook
TypeScript
41
star
15

vue-frag-plugin

Webpack/Rollup/Vite plugin to add multiple root-node support to Vue 2 SFCs
TypeScript
41
star
16

instant-mocha

☕️ Build tests with Webpack and run with Mocha in one command
TypeScript
41
star
17

resolve-pkg-maps

Resolve package.json `exports` & `imports` maps
TypeScript
39
star
18

git-publish

☁️ Publish your npm package to a GitHub repository branch
TypeScript
38
star
19

compare-bun-node

Comparison of Bun's API against Node.js's
JavaScript
38
star
20

VisualQuery

Light & minimal front-end query builder for jQuery
JavaScript
38
star
21

webpack-localize-assets-plugin

🌐 Localize your Webpack bundle with multiple locales
TypeScript
38
star
22

webpack-json-access-optimizer

Webpack plugin to tree-shake and minify JSON modules
TypeScript
37
star
23

terminal-columns

Render readable & responsive tables in the terminal
TypeScript
32
star
24

deps

📦🔍 Analyze which package.json dependencies are in-use with V8 Coverage 🔥
TypeScript
31
star
25

vue-pseudo-window

🖼 Declaratively interface window/document/body in your Vue template
JavaScript
31
star
26

manten

💮 満点 - Lightweight testing library for Node.js
TypeScript
29
star
27

svg-browser-export

Export SVG to PNG, JPEG, or WEBP in the browser
TypeScript
23
star
28

comment-mark

Interpolate strings with HTML comment markers!
TypeScript
23
star
29

npm-multi-publish

Publish an npm package to multiple registries
JavaScript
23
star
30

reactive-json-file

💎 Reactively sync JSON mutations to disk
TypeScript
23
star
31

playwright-start

Start a long-running Playwright browser server via CLI
TypeScript
22
star
32

ink-task-list

Task runner components for Ink
TypeScript
22
star
33

chainset

Set object values using property chaining syntax
TypeScript
21
star
34

build-this-branch

🤖 Script to automate creating built branches
TypeScript
21
star
35

vue-vnode-syringe

🧬 Add attributes and event-listeners to <slot> content 💉
JavaScript
20
star
36

vue-dom-hints

Vue.js devtool for identifying Vue components and their SFC paths in the DOM
JavaScript
20
star
37

vue-grep

Grep your Vue.js codebase with CSS selectors
TypeScript
19
star
38

git-squash-branch

Script to squash the commits in the current Git branch
TypeScript
17
star
39

fs-fixture

Easily create test fixtures at a temporary file-system path
TypeScript
16
star
40

vue-split-view

Create a resizable split-view to partition the UI
Vue
16
star
41

alias-imports

Create Node.js aliases via imports map
TypeScript
16
star
42

vue-import-loader

🌐 Webpack loader to automatically detect & import used components
JavaScript
13
star
43

fs-require

Create a require() function from any file-system. Great for in-memory fs testing!
TypeScript
13
star
44

pkg-entry-points

Get all entry-points for an npm package. Supports the `exports` field in `package.json`
TypeScript
13
star
45

vue-subslot

💍 Pick out specific elements from the component <slot>
JavaScript
12
star
46

gh-emojis

Use GitHub emojis from their API as an npm package
JavaScript
12
star
47

litemark

🖋 GitHub Flavored Markdown Editor
Vue
12
star
48

hirok.io

👤 My personal website & blog
Vue
11
star
49

vue-proxi

💠 Tiny proxy component for Vue.js
JavaScript
11
star
50

bfs

Find the path of a value in a complex JavaScript object graph/tree.
JavaScript
11
star
51

prerelease-checks

Run essential pre-release checks before releasing an npm package
TypeScript
11
star
52

git-detect-case-change

🤖 Script to detect file name case changes in a Git repository
TypeScript
10
star
53

cli-simple-table

Simple CLI table for simple people
TypeScript
9
star
54

webpack-test-utils

Utility functions to test Webpack loaders/plugins
TypeScript
8
star
55

vue-svg-icon-set

Efficiently expose a SVG icon set in Vue
JavaScript
8
star
56

webpack-playground

Demonstration of different Webpack configurations
JavaScript
8
star
57

eslint-config

TypeScript
7
star
58

vue-v

Tiny component to render Vue.js vNodes in the template.
JavaScript
7
star
59

i-peers

npx package to install local peer-dependencies
JavaScript
7
star
60

fs.promises.exists

🪐 The missing fs.promises.exists(). Also supports case-sensitive/insensitive file paths.
TypeScript
7
star
61

vue-just-ssr

🔥 Instantly add a Vue SSR dev-env to your Webpack build
JavaScript
7
star
62

issue-reproductions

A repository to collect and organize my issue reproductions
JavaScript
6
star
63

webpack-analyze-duplication-plugin

Detect duplicated modules in your Webpack build
JavaScript
6
star
64

vue-feather-icon-set

Optimized Feather icon set for Vue using SVG references
JavaScript
6
star
65

is-fs-case-sensitive

Check whether the file-system is case-sensitive
TypeScript
6
star
66

npm-registry-sync

A daemon to sync packages across npm registries
TypeScript
6
star
67

babel-plugin-debug-object-location

Babel plugin to help you determine where an object or array was instantiated
TypeScript
5
star
68

generate-batched-pr-manifest

Generate a manifest of all the PRs included in a batched PR
TypeScript
5
star
69

entry-file-plugin

Create an ESM entry-file in your Webpack build to consolidate entry-point exports
TypeScript
5
star
70

privatenumber

5
star
71

webpack-dependency-size

👩‍🔬 Webpack plugin to get an overview of bundled dependencies and their size
JavaScript
5
star
72

vue-demo-collapse

Vue component that shows a demo and a "Show Code" button to expand source code
Vue
4
star
73

markdown-it-add-attrs

markdown-it plugin to add attributes to all rendered elements
JavaScript
4
star
74

browser-reload-plugin

Automatically reload the browser page on every Webpack watch build
JavaScript
4
star
75

rollup-playground

Demonstration of different Rollup configurations
JavaScript
3
star
76

rollup-plugin-htmlvue

Rollup plugin for transforming HTML/XML to Vue SFC
TypeScript
3
star
77

htmlvue-loader

Webpack loader for compiling HTML to Vue
JavaScript
3
star
78

vue-ast-utils

Utils for working with Vue 3 AST nodes
TypeScript
3
star
79

systemjs-unpkg

SystemJS extra to auto-resolve bare specifiers to UNPKG
JavaScript
3
star
80

web-diff

Visually diff web pages
JavaScript
2
star
81

rollup-plugin-aggregate-exports

Emit an entry file to aggregate exports across multiple files.
JavaScript
2
star
82

svg-trace-loader

Webpack loader to trace and flatten SVGs into one path
JavaScript
2
star
83

repkg

🚚 On-demand AMD npm package bundling service
JavaScript
2
star
84

postcss-custom-properties-transformer

PostCSS plugin to apply transformations to CSS custom properties (eg. mangling)
JavaScript
2
star
85

webpack-distsize

Track Webpack output size via version control
JavaScript
2
star
86

motion-orientation-api

Motion & Orientation API explorer
Vue
2
star
87

vue-server-renderer

JavaScript
2
star
88

postcss-import-alias

Use aliases in your PostCSS import statements
JavaScript
2
star
89

pm2-no-daemon-bug

JavaScript
1
star
90

resume

1
star
91

fs-router-patch

Add routing for shimming fs access
JavaScript
1
star
92

gulp-watchman

JavaScript
1
star
93

.github

1
star
94

sharp-vs-resvgjs

JavaScript
1
star
95

mempack

Run a Webpack build in-memory
JavaScript
1
star