MCPcopy Index your code
hub / github.com/developit/microbundle

github.com/developit/microbundle @v0.15.1

Chat with this repo
repository ↗ · DeepWiki ↗ · release v0.15.1 ↗ · + Follow
124 symbols 247 edges 118 files 1 documented · 1% 57 cross-repo links updated 5mo agov0.15.1 · 2022-08-12★ 8,13476 open issues
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

microbundle

Microbundle npm travis

The zero-configuration bundler for tiny modules, powered by Rollup.


Guide → SetupFormatsModern ModeUsage & ConfigurationAll Options


✨ Features

  • One dependency to bundle your library using only a package.json
  • Support for ESnext & async/await (via [Babel] & [async-to-promises])
  • Produces tiny, optimized code for all inputs
  • Supports multiple entry modules (cli.js + index.js, etc)
  • Creates multiple output formats for each entry (CJS, UMD & ESM)
  • 0 configuration TypeScript support
  • Built-in Terser compression & gzipped bundle size tracking

🔧 Installation & Setup

1️⃣ Install by running: npm i -D microbundle

2️⃣ Set up your package.json:

{
  "name": "foo",                      // your package name
  "type": "module",
  "source": "src/foo.js",             // your source code
  "exports": {
    "require": "./dist/foo.cjs",      // used for require() in Node 12+
    "default": "./dist/foo.modern.js" // where to generate the modern bundle (see below)
  },
  "main": "./dist/foo.cjs",           // where to generate the CommonJS bundle
  "module": "./dist/foo.module.js",   // where to generate the ESM bundle
  "unpkg": "./dist/foo.umd.js",       // where to generate the UMD bundle (also aliased as "umd:main")
  "scripts": {
    "build": "microbundle",           // compiles "source" to "main"/"module"/"unpkg"
    "dev": "microbundle watch"        // re-build when source files change
  }
}

3️⃣ Try it out by running npm run build.

💽 Output Formats

Microbundle produces esm, cjs, umd bundles with your code compiled to syntax that works pretty much everywhere. While it's possible to customize the browser or Node versions you wish to support using a browserslist configuration, the default setting is optimal and strongly recommended.

🤖 Modern Mode

In addition to the above formats, Microbundle also outputs a modern bundle specially designed to work in all modern browsers. This bundle preserves most modern JS features when compiling your code, but ensures the result runs in 95% of web browsers without needing to be transpiled. Specifically, it uses Babel's "bugfixes" mode (previously known as preset-modules) to target the set of browsers that support <script type="module"> - that allows syntax like async/await, tagged templates, arrow functions, destructured and rest parameters, etc. The result is generally smaller and faster to execute than the plain esm bundle.

Take the following source code for example:

// Our source, "src/make-dom.js":
export default async function makeDom(tag, props, children) {
    let el = document.createElement(tag);
    el.append(...(await children));
    return Object.assign(el, props);
}

Compiling the above using Microbundle produces the following modern and esm bundles:

make-dom.modern.js (117b) make-dom.module.js (194b)
export default async function (e, t, a) {
    let n = document.createElement(e);
    n.append(...(await a));
    return Object.assign(n, t);
}
export default function (e, t, r) {
    try {
        var n = document.createElement(e);
        return Promise.resolve(r).then(function (e) {
            return n.append.apply(n, e), Object.assign(n, t);
        });
    } catch (e) {
        return Promise.reject(e);
    }
}

This is enabled by default. All you have to do is add an "exports" field to your package.json:

{
    "main": "./dist/foo.umd.js", // legacy UMD output (for Node & CDN use)
    "module": "./dist/foo.module.mjs", // legacy ES Modules output (for bundlers)
    "exports": "./dist/foo.modern.mjs", // modern ES2017 output
    "scripts": {
        "build": "microbundle src/foo.js"
    }
}

The "exports" field can also be an object for packages with multiple entry modules:

{
    "name": "foo",
    "exports": {
        ".": "./dist/foo.modern.mjs", // import "foo" (the default)
        "./lite": "./dist/lite.modern.mjs", // import "foo/lite"
        "./full": "./dist/full.modern.mjs" // import "foo/full"
    },
    "scripts": {
        "build": "microbundle src/*.js" // build foo.js, lite.js and full.js
    }
}

📦 Usage & Configuration

Microbundle includes two commands - build (the default) and watch. Neither require any options, but you can tailor things to suit your needs a bit if you like.

  • microbundle – bundles your code once and exits. (alias: microbundle build)
  • microbundle watch – bundles your code, then re-bundles when files change.

ℹ️ Microbundle automatically determines which dependencies to inline into bundles based on your package.json.

Read more about How Microbundle decides which dependencies to bundle, including some example configurations.

Specifying filenames in package.json

Unless overridden via the command line, microbundle uses the source property in your package.json to determine which of your JavaScript files to start bundling from (your "entry module"). The filenames and paths for generated bundles in each format are defined by the main, umd:main, module and exports properties in your package.json.

{
  "source": "src/index.js",             // input
  "main": "dist/foo.js",                // CommonJS output bundle
  "umd:main": "dist/foo.umd.js",        // UMD output bundle
  "module": "dist/foo.mjs",           // ES Modules output bundle
  "exports": {
    "require": "./dist/foo.js",         // CommonJS output bundle
    "default": "./dist/foo.modern.mjs", // Modern ES Modules output bundle
  },
  "types": "dist/foo.d.ts"              // TypeScript typings directory
}

When deciding which bundle to use, Node.js 12+ and webpack 5+ will prefer the exports property, while older Node.js releases use the main property, and other bundlers prefer the module field. For more information about the meaning of the different properties, refer to the Node.js documentation.

For UMD builds, microbundle will use a camelCase version of the name field in your package.json as export name. Alternatively, this can be explicitly set by adding an "amdName" key in your package.json, or passing the --name command line argument.

Usage with {"type":"module"} in package.json

Node.js 12.16+ adds a new "ES Module package", which can be enabled by adding {"type":"module"} to your package.json. This property changes the default source type of .js files to be ES Modules instead of CommonJS. When using {"type":"module"}, the file extension for CommonJS bundles generated by Microbundle must be changed to .cjs:

{
  "type": "module",
  "module": "dist/foo.js",  // ES Module bundle
  "main": "dist/foo.cjs",   // CommonJS bundle
}

Additional Configuration Options

Config also can be overridded by the publishConfig property in your package.json.

{
  "main": "src/index.ts",          // this would be used in the dev environment (e.g. Jest)
  "publishConfig": {
    "source": "src/index.js",      // input
    "main": "dist/my-library.js",  // output
  },
  "scripts": {
    "build": "microbundle"
  }
}

Building a single bundle with fixed output name

By default Microbundle outputs multiple bundles, one bundle per format. A single bundle with a fixed output name can be built like this:

microbundle -i lib/main.js -o dist/bundle.js --no-pkg-main -f umd

Using with TypeScript

Just point the input to a .ts file through either the cli or the source key in your package.json and you’re done.

Microbundle will generally respect your TypeScript config defined in a tsconfig.json file with notable exceptions being the "target" and "module" settings. To ensure your TypeScript configuration matches the configuration that Microbundle uses internally it's strongly recommended that you set "module": "ESNext" and "target": "ESNext" in your tsconfig.json.

To ensure Microbundle does not process extraneous files, by default it only includes your entry point. If you want to include other files for compilation, such as ambient declarations, make sure to add either "files" or "include" into your tsconfig.json.

If you're using TypeScript with CSS Modules, you will want to set "include": ["node_modules/microbundle/index.d.ts"] in your tsconfig.json to tell TypeScript how to handle your CSS Module imports.

CSS and CSS Modules

Importing CSS files is supported via import "./foo.css". By default, generated CSS output is written to disk. The --css inline command line option will inline generated CSS into your bundles as a string, returning the CSS string from the import:

// with the default external CSS:
import './foo.css'; // generates a minified .css file in the output directory

// with `microbundle --css inline`:
import css from './foo.css';
console.log(css); // the generated minified stylesheet

CSS Modules: CSS files with names ending in .module.css are treated as a CSS Modules. To instead treat imported .css files as modules, run Microbundle with --css-modules true. To disable CSS Modules for your project, pass --no-css-modules or --css-modules false.

The default scope name for CSS Modules is_[name]__[local]__[hash:base64:5] in watch mode, and _[hash:base64:5] for production builds. This can be customized by passing the command line argument --css-modules "[name]_[hash:base64:7]", using these fields and naming conventions.

flag import is css module?
null import './my-file.css'; :x:
null import './my-file.module.css'; :white_check_mark:
false import './my-file.css'; :x:
false import './my-file.module.css'; :x:
true import './my-file.css'; :white_check_mark:
true import './my-file.module.css'; :white_check_mark:

Building Module Workers

Microbundle is able to detect and bundle Module Workers when generating bundles in the esm and modern formats. To use this feature, instantiate your Web Worker as follows:

worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });
// or simply:
worker = new Worker('./worker.js', { type: 'module' });

... then add the --workers flag to your build command:

microbundle --workers

For more information see @surma/rollup-plugin-off-main-thread.

Visualize Bundle Makeup

Use the --visualize flag to generate a stats.html file at build time, showing the makeup of your bundle. Uses rollup-plugin-visualizer.

Mangling Properties

To achieve the smallest possible bundle size, libraries often wish to rename internal object properties or class members to smaller names - transforming this._internalIdValue to this._i. Microbundle doesn't do this by default, however it can be enabled by creating a mangle.json file (or a "mangle" property in your package.json). Within that file, you can specify a regular expression pattern to control which properties should be mangled. For example: to mangle all property names beginning an underscore:

{
    "mangle": {
        "regex": "^_"
    }
}

It's also possible to configure repeatable short names for each mangled property, so that every build of your library has the same output. See the wiki for a complete guide to property mangling in Microbundle.

Defining build-time constants

The --define option can be used to inject or replace build-time constants when bundling. In addition to injecting string or number constants, prefixing the define name with @ allows injecting JavaScript expressions.

Extension points exported contracts — how you extend this code

Driveable (Interface)
(no doc) [3 implementers]
test/fixtures/ts-mixed-exports/src/car.ts
Driveable (Interface)
(no doc) [3 implementers]
test/fixtures/basic-ts/src/car.ts

Core symbols most depended-on inside this repo

replaceName
called by 4
src/index.js
isDir
called by 3
src/utils.js
getBuildScript
called by 2
tools/build-fixture.js
buildDirectory
called by 2
tools/build-fixture.js
two
called by 2
test/fixtures/no-pkg/src/two.js
two
called by 2
test/fixtures/custom-source-with-cwd/custom-source/src/two.js
two
called by 2
test/fixtures/no-pkg-name/src/two.js
two
called by 2
test/fixtures/basic-no-pkg-main/src/two.js

Shape

Function 96
Class 16
Method 10
Interface 2

Languages

TypeScript100%

Modules by API surface

src/index.js17 symbols
test/fixtures/ts-mixed-exports/src/car.ts5 symbols
test/fixtures/jsx/index.js5 symbols
test/fixtures/class-decorators-ts/src/index.ts5 symbols
test/fixtures/basic-ts/src/car.ts5 symbols
src/utils.js5 symbols
test/fixtures/basic-tsx/src/index.tsx4 symbols
src/lib/transform-fast-rest.js4 symbols
src/lib/babel-custom.js4 symbols
test/index.test.js3 symbols
test/fixtures/terser-annotations/src/index.js3 symbols
test/fixtures/custom-babelrc/src/index.js3 symbols

Dependencies from manifests, versioned

@babel/cli7.12.10 · 1×
@babel/core7.12.10 · 1×
@babel/node7.12.10 · 1×
@babel/plugin-proposal-class-properties7.12.1 · 1×
@babel/plugin-proposal-throw-expressions7.12.1 · 1×
@babel/plugin-syntax-import-meta7.10.4 · 1×
@babel/plugin-syntax-jsx7.12.1 · 1×
@babel/plugin-transform-flow-strip-types7.12.10 · 1×
@babel/plugin-transform-react-jsx7.12.11 · 1×
@babel/plugin-transform-regenerator7.12.1 · 1×
@babel/preset-env7.12.11 · 1×
@babel/preset-flow7.12.1 · 1×

For agents

$ claude mcp add microbundle \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact