📦 🍣 Zero-config JS bundler for ESM, CommonJS, and .d.ts outputs. (Forked from pkgroll)

Overview

📦 🍣 puild (A fork of pkgroll)

Write your code in ESM & TypeScript and bundle it to get ESM, CommonJS, and type declaration outputs with a single command!

Features

  • Zero config Configuration automatically inferred from package.json
  • ESM/CJS Detection Uses .mjs/.cjs extension or package.json#type to infer module type
  • Export & Import maps Uses export and import maps to configure endpoints and aliases
  • TypeScript friendly Transform TS and emit .d.ts files (Supports .cts/.mts too!)
  • Node.js ESM ⇄ CJS friendly Preserves named exports from ESM to CJS
  • Fast Transformations powered by esbuild

Install

npm install --save-dev puild

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.

    Puild 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/file.js",
  "module": "./dist/file.mjs",
  "types": "./dist/file.d.ts",

  // Define output files for Node.js export maps (https://nodejs.org/api/packages.html#exports)
  "exports": {
    "types": "./dist/file.d.ts",
    "require": "./dist/file.js",
    "import": "./dist/file.mjs"
  },

  // bin files will be compiled to be executable with the Node.js hashbang
  "bin": "./dist/cli.js",

  // (Optional) Add a build script referencing `puild`
  "scripts": {
    "build": "puild"
  }

  // ...
}

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

  1. Package build!
npm run build # or npx puild

Usage

Entry-points

Puild 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

Puild 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. Puild 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 Puild 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

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

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

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

puild --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 puild 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, Puild 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:

puild --env.NODE_ENV=production

Minification

Pass in the --minify flag to minify assets.

puild --minify

Watch mode

Run the bundler in watch mode during development:

puild --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 for it to be resolved by the consumer.

    This can be unintuitive because types are a development enhancement and also adds installation bloat. Bundling filters out unused types and allows type dependencies to be declared in devDependencies.

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

Credits

Hiroki Osame Ray

You might also like...

Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

Jan 3, 2023

A new zero-config test runner for the true minimalists

Why User-friendly - zero-config, no API to learn, simple conventions Extremely lighweight - only 40 lines of code and no dependencies Super fast - wit

Dec 20, 2022

Zero-config PWA Plugin for VitePress

Zero-config PWA Plugin for VitePress

Zero-config PWA Plugin for VitePress 🚀 Features 📖 Documentation & guides 👌 Zero-Config: sensible built-in default configs for common use cases 🔩 E

Dec 1, 2022

Vite plugin to client bundle i18next locales composited from one to many json/yaml files from one to many libraries. Zero config HMR support included.

vite-plugin-i18next-loader yarn add -D vite-plugin-i18next-loader Vite plugin to client bundle i18next locales composited from one to many json/yaml f

Nov 30, 2022

Framework for interacting with instagrams private api in a usable manner (forked from andre's work and improved and fixed)

node-ig-framework Framework for interacting with instagrams private api in a usable manner (forked from andre's work and improved and fixed) Installat

Dec 31, 2022

This work is an overnight with 84436, an overlay code forked from Osu! community but for ``flag of Vietnam`` in r/place 2022

This work is an overnight with 84436, an overlay code forked from Osu! community but for ``flag of Vietnam`` in r/place 2022

flag-of-vietnam-rplace2022 This work is a overnight with 84436, an overlay code forked from Osu! community but for flag of Vietnam Installation Xài Ta

Nov 2, 2022

Macarena finance is a simple UI for Yearn Finance, made to be forked!

Macarena finance is a simple UI for Yearn Finance, made to be forked!

Macarena Finance Macarena finance is a simple UI for Yearn Finance, made to be forked! Running your own instance of Yearn makes you eligible to earn f

Oct 1, 2022

Custom Vitest matchers to test the state of the DOM, forked from jest-dom.

vitest-dom Custom Vitest matchers to test the state of the DOM This library is a fork of @testing-library/jest-dom. It shares that library's implement

Dec 16, 2022

forked from https://github.com/ecomfe/fontmin

@sctg/fontminify (just a minimal change to original) Minify font seamlessly Original homepage English 简体中文 繁體中文 日本語 한국어 Install $ npm install --save @

Oct 12, 2022
Comments
  • Configure Renovate

    Configure Renovate

    Mend Renovate

    Welcome to Renovate! This is an onboarding PR to help you understand and configure settings before regular Pull Requests begin.

    🚦 To activate Renovate, merge this Pull Request. To disable Renovate, simply close this Pull Request unmerged.


    Detected Package Files

    • .github/workflows/release.yml (github-actions)
    • .github/workflows/test.yml (github-actions)
    • package.json (npm)

    Configuration Summary

    Based on the default config's presets, Renovate will:

    • Start dependency updates only once this onboarding PR is merged
    • Enable Renovate Dependency Dashboard creation.
    • If Renovate detects semantic commits, it will use semantic commit type fix for dependencies and chore for all others.
    • Ignore node_modules, bower_components, vendor and various test/tests directories.
    • Autodetect whether to pin dependencies or maintain ranges.
    • Rate limit PR creation to a maximum of two per hour.
    • Limit to maximum 10 open PRs at any time.
    • Group known monorepo packages together.
    • Use curated list of recommended non-monorepo package groupings.
    • A collection of workarounds for known problems with packages.

    🔡 Would you like to change the way Renovate is upgrading your dependencies? Simply edit the renovate.json in this branch with your custom config and the list of Pull Requests in the "What to Expect" section below will be updated the next time Renovate runs.


    What to Expect

    With your current configuration, Renovate will create 18 Pull Requests:

    chore(deps): update dependency @so1ve/eslint-config to ^0.32.0
    • Schedule: ["at any time"]
    • Branch name: renovate/so1ve-eslint-config-0.x
    • Merge into: main
    • Upgrade @so1ve/eslint-config to ^0.32.0
    chore(deps): update dependency manten to ^0.6.0
    • Schedule: ["at any time"]
    • Branch name: renovate/manten-0.x
    • Merge into: main
    • Upgrade manten to ^0.6.0
    chore(deps): update dependency vitest to ^0.25.0
    • Schedule: ["at any time"]
    • Branch name: renovate/vitest-monorepo
    • Merge into: main
    • Upgrade vitest to ^0.25.0
    fix(deps): update dependency esbuild to ^0.16.0
    • Schedule: ["at any time"]
    • Branch name: renovate/esbuild-0.x
    • Merge into: main
    • Upgrade esbuild to ^0.16.0
    fix(deps): update dependency magic-string to ^0.27.0
    • Schedule: ["at any time"]
    • Branch name: renovate/magic-string-0.x
    • Merge into: main
    • Upgrade magic-string to ^0.27.0
    chore(deps): update actions/checkout action to v3
    • Schedule: ["at any time"]
    • Branch name: renovate/actions-checkout-3.x
    • Merge into: main
    • Upgrade actions/checkout to v3
    chore(deps): update actions/setup-node action to v3
    • Schedule: ["at any time"]
    • Branch name: renovate/actions-setup-node-3.x
    • Merge into: main
    • Upgrade actions/setup-node to v3
    chore(deps): update dependency rollup-plugin-dts to v5
    • Schedule: ["at any time"]
    • Branch name: renovate/rollup-plugin-dts-5.x
    • Merge into: main
    • Upgrade rollup-plugin-dts to ^5.0.0
    chore(deps): update dependency type-fest to v3
    • Schedule: ["at any time"]
    • Branch name: renovate/type-fest-3.x
    • Merge into: main
    • Upgrade type-fest to ^3.0.0
    chore(deps): update dependency vite to v4
    • Schedule: ["at any time"]
    • Branch name: renovate/vite-4.x
    • Merge into: main
    • Upgrade vite to ^4.0.0
    fix(deps): update dependency @​rollup/plugin-alias to v4
    • Schedule: ["at any time"]
    • Branch name: renovate/rollup-plugin-alias-4.x
    • Merge into: main
    • Upgrade @rollup/plugin-alias to ^4.0.0
    fix(deps): update dependency @​rollup/plugin-commonjs to v23
    • Schedule: ["at any time"]
    • Branch name: renovate/rollup-plugin-commonjs-23.x
    • Merge into: main
    • Upgrade @rollup/plugin-commonjs to ^23.0.0
    fix(deps): update dependency @​rollup/plugin-inject to v5
    • Schedule: ["at any time"]
    • Branch name: renovate/rollup-plugin-inject-5.x
    • Merge into: main
    • Upgrade @rollup/plugin-inject to ^5.0.0
    fix(deps): update dependency @​rollup/plugin-json to v5
    • Schedule: ["at any time"]
    • Branch name: renovate/rollup-plugin-json-5.x
    • Merge into: main
    • Upgrade @rollup/plugin-json to ^5.0.0
    fix(deps): update dependency @​rollup/plugin-node-resolve to v15
    • Schedule: ["at any time"]
    • Branch name: renovate/rollup-plugin-node-resolve-15.x
    • Merge into: main
    • Upgrade @rollup/plugin-node-resolve to ^15.0.0
    fix(deps): update dependency @​rollup/plugin-replace to v5
    • Schedule: ["at any time"]
    • Branch name: renovate/rollup-plugin-replace-5.x
    • Merge into: main
    • Upgrade @rollup/plugin-replace to ^5.0.0
    fix(deps): update dependency @​rollup/pluginutils to v5
    • Schedule: ["at any time"]
    • Branch name: renovate/rollup-pluginutils-5.x
    • Merge into: main
    • Upgrade @rollup/pluginutils to ^5.0.0
    fix(deps): update dependency rollup to v3
    • Schedule: ["at any time"]
    • Branch name: renovate/rollup-3.x
    • Merge into: main
    • Upgrade rollup to ^3.0.0

    🚸 Branch creation will be limited to maximum 2 per hour, so it doesn't swamp any CI resources or spam the project. See docs for prhourlylimit for details.


    ❓ Got questions? Check out Renovate's Docs, particularly the Getting Started section. If you need any further assistance then you can also request help here.


    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 0
Owner
ʀᴀʏ
AAwwwwwwwwwwww
ʀᴀʏ
Forked from hayes0724/shopify-packer Modern development tool for Shopify using Webpack 5. Easy to extend and customize, zero build config, compatible with Slate and existing websites.

Shopify Packer Modern development tool for Shopify using Webpack 5. Easy to extend and customize, zero build config, comes with starter themes and com

Web & Mobile | eCommerce | Full-Stack Developer 4 Nov 24, 2022
An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

Snyk Labs 57 Dec 28, 2022
Universal importer for CommonJS and ESM in Node.js

ModuleImporter by Nicholas C. Zakas If you find this useful, please consider supporting my work with a donation. Description A utility for seamlessly

Human Who Codes 18 Dec 2, 2022
utility library for promise, support both commonjs and ESM

promising-utils A utility library for promise, supports both commonjs and ESM npm install promising-utils --save yarn add promising-utils wait Used wh

Qiang Li 4 Oct 18, 2022
Node.js loader for compiling ESM & TypeScript modules to CommonJS

cjs-loader Node.js require() hook to instantaneously transform ESM & TypeScript to CommonJS on demand using esbuild. Features Transforms ESM & TypeScr

esbuild kit 40 Dec 13, 2022
Recursively publish ESM packages as CommonJS!

Commonify.js For us who are still relying on CommonJS, or using Electron which does not support ESM. ?? See also build-electron I made this tool that

Mikael Finstad 31 Dec 29, 2022
Minimal utility to convert to or from any timezone. Deno/Node/Browser. ESM/CommonJS.

minitz Features Convert dates between any timezone supported by the system. Parses ISO8601 time strings. MIT licensed, use the library any way you wan

Hexagon 14 Oct 10, 2022
Babel plugin and helper functions for interoperation between Node.js native ESM and Babel ESM

babel-plugin-node-cjs-interop and node-cjs-interop: fix the default import interoperability issue in Node.js The problem to solve Consider the followi

Masaki Hara 15 Nov 6, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022