• Stars
    star
    7,933
  • Rank 4,459 (Top 0.1 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated 17 days ago

Reviews

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

Repository Details

📦 Zero-configuration bundler for tiny modules.

microbundle

Microbundle npm travis licenses

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": {
    "types": "./dist/foo.d.ts",         // TypeScript typings for NodeNext modules
    "require": "./dist/foo.js",         // CommonJS output bundle
    "default": "./dist/foo.modern.mjs", // Modern ES Modules output bundle
  },
  "types": "dist/foo.d.ts"              // TypeScript typings
}

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.

To ensure that your module's .d.ts type info is visible to other TypeScript projects that use moduleResolution: 'NodeNext', add a types key to your package.json's corresponding exports mapping.

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';
null import './my-file.module.css';
false import './my-file.css';
false import './my-file.module.css';
true import './my-file.css';
true import './my-file.module.css';

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.

Build command Source code Output
microbundle --define VERSION=2 console.log(VERSION) console.log(2)
microbundle --define API_KEY='abc123' console.log(API_KEY) console.log("abc123")
microbundle --define @assign=Object.assign assign(a, b) Object.assign(a, b)

All CLI Options

Usage
	$ microbundle <command> [options]

Available Commands
	build    Build once and exit
	watch    Rebuilds on any change

For more info, run any command with the `--help` flag
	$ microbundle build --help
	$ microbundle watch --help

Options
	-v, --version      Displays current version
	-i, --entry        Entry module(s)
	-o, --output       Directory to place build files into
	-f, --format       Only build specified formats (any of modern,esm,cjs,umd or iife) (default modern,esm,cjs,umd)
	-w, --watch        Rebuilds on any change  (default false)
	--pkg-main         Outputs files analog to package.json main entries  (default true)
	--target           Specify your target environment (node or web)  (default web)
	--external         Specify external dependencies, or 'none' (default peerDependencies and dependencies in package.json)
	--globals          Specify globals dependencies, or 'none'
	--define           Replace constants with hard-coded values (use @key=exp to replace an expression)
	--alias            Map imports to different modules
	--compress         Compress output using Terser (default true when --target is web, false when --target is node)
	--strict           Enforce undefined global context and add "use strict"
	--name             Specify name exposed in UMD and IIFE builds
	--cwd              Use an alternative working directory  (default .)
	--sourcemap        Generate source map  (default true)
	--raw              Show raw byte size  (default false)
	--jsx              A custom JSX pragma like React.createElement (default h)
	--jsxFragment      A custom JSX fragment pragma like React.Fragment (default Fragment)
	--jsxImportSource  Declares the module specifier to be used for importing jsx factory functions
	--tsconfig         Specify the path to a custom tsconfig.json
	--generateTypes    Whether or not to generate types, if `types` or `typings` is set in `package.json` then it will default to be `true`
	--css              Where to output CSS: "inline" or "external" (default "external")
	--css-modules      Configures .css to be treated as modules (default null)
	--workers          Bundle module workers - see https://github.com/surma/rollup-plugin-off-main-thread#auto-bundling  (default false)
	--visualize        Generate bundle makeup visualization (stats.html)
	-h, --help         Displays this message

Examples
	$ microbundle build --globals react=React,jquery=$
	$ microbundle build --define API_KEY=1234
	$ microbundle build --alias react=preact/compat
	$ microbundle watch --no-sourcemap # don't generate sourcemaps
	$ microbundle build --tsconfig tsconfig.build.json

🛣 Roadmap

Here's what's coming up for Microbundle:

🔨 Built with Microbundle

🥂 License

MIT

More Repositories

1

mitt

🥊 Tiny 200 byte functional event emitter / pubsub.
TypeScript
9,030
star
2

htm

Hyperscript Tagged Markup: JSX alternative using standard tagged templates, with compiler support.
JavaScript
8,500
star
3

unfetch

🐕 Bare minimum 500b fetch polyfill.
JavaScript
5,637
star
4

greenlet

🦎 Move an async function into its own thread.
JavaScript
4,621
star
5

workerize

🏗️ Run a module in a Web Worker.
JavaScript
4,287
star
6

redaxios

The Axios API, as an 800 byte Fetch wrapper.
JavaScript
4,131
star
7

unistore

🌶 350b / 650b state container with component actions for Preact & React
JavaScript
2,865
star
8

express-es6-rest-api

🔋 Starter project for an ES6 RESTful Express API.
JavaScript
2,455
star
9

workerize-loader

🏗️ Automatically move a module into a Web Worker (Webpack loader)
JavaScript
2,283
star
10

snarkdown

😼 A snarky 1kb Markdown parser written in JavaScript
JavaScript
2,180
star
11

stockroom

🗃 Offload your store management to a worker easily.
JavaScript
1,758
star
12

dlv

Safe deep property access in 120 bytes. x = dlv(obj, 'a.b.x')
JavaScript
1,217
star
13

karmatic

🦑 Easy automatic (headless) browser testing with Jest's API, but powered by Karma & Webpack.
JavaScript
1,181
star
14

decko

💨 The 3 most useful ES7 decorators: bind, debounce and memoize
JavaScript
1,038
star
15

preact-boilerplate

🎸 Ready-to-rock Preact starter project, powered by Webpack.
JavaScript
976
star
16

web-worker

Consistent Web Workers in browser and Node.
JavaScript
949
star
17

vhtml

Render JSX/Hyperscript to HTML strings, without VDOM 🌈
JavaScript
740
star
18

histore

🏬 200b key-value store backed by navigation state
JavaScript
677
star
19

optimize-plugin

Optimized Webpack Bundling for Everyone. Intro ⤵️
JavaScript
661
star
20

undom

🍩 1kb minimally viable DOM Document implementation
JavaScript
654
star
21

asyncro

⛵️ Beautiful Array utilities for ESnext async/await ~
JavaScript
493
star
22

nextjs-preact-demo

Next.js 9.3 + Preact = 21kB
JavaScript
384
star
23

tags-input

🔖 <input type="tags"> like magic
JavaScript
329
star
24

linkstate

Bind events to state. Works with Preact and React.
JavaScript
296
star
25

preact-redux

➿ Preact integration for Redux (no shim needed!)
JavaScript
288
star
26

task-worklet

Task Worklet: explainer, polyfill and demos.
JavaScript
274
star
27

jsdom-worker

👷‍♀️ Use Web Workers in Jest / JSDOM 🌈
JavaScript
273
star
28

preact-worker-demo

Demo of preact rendering an entire app in a Web Worker.
JavaScript
217
star
29

preact-virtual-list

📇 Virtual List that only renders visible items. Supports millions of rows.
JavaScript
215
star
30

jsxobj

Build JSON using JSX 🌈 (may contain blood magic)
JavaScript
214
star
31

preact-redux-example

🔁 Preact + Redux Example Project
JavaScript
201
star
32

preact-markup

⚡ Render HTML5 as VDOM, with Components as Custom Elements!
JavaScript
195
star
33

simple-element-resize-detector

Observes element size changes using a hidden iframe
JavaScript
190
star
34

preact-mdl

💥 A collection of Preact Components that encapsulate Google's Material Design Lite.
JavaScript
186
star
35

zero-to-preact

A Step-by-step Guide to Preact + Webpack 2, without boilerplate!
JavaScript
179
star
36

state-machine-component

⚙️ State machine -powered components in 250 bytes
JavaScript
177
star
37

preact-portal

📡 Render Preact components in (a) SPACE 🌌 🌠
JavaScript
176
star
38

preact-photon

🚀 Beautiful desktop apps with Preact + Photon ❤️
JavaScript
173
star
39

preact-slots

🕳 Render Preact trees into other Preact trees, like portals.
JavaScript
157
star
40

oss.ninja

👩‍⚖️ Dynamic licenses for your projects - no more LICENSE.txt!
JavaScript
146
star
41

preact-cycle

♻️ Minimal functional Virtual DOM rendering using Preact 🚲
JavaScript
131
star
42

babel-preset-modernize

JavaScript
122
star
43

dropfox

🦊 📂 A dropbox client powered by Preact, Electron and Photon
JavaScript
122
star
44

preact-scroll-viewport

Preact Component that renders homogeneous children only when visible
JavaScript
121
star
45

resource-router-middleware

🚴 Express REST resources as middleware mountable anywhere
JavaScript
120
star
46

object-diff-patch

JavaScript
103
star
47

preact-todomvc

💣 TodoMVC done in Preact. Under 6kb and fast.
JavaScript
102
star
48

restful-mongoose

🐦 Expose Mongoose models as RESTful Express resources.
JavaScript
90
star
49

modify-babel-preset

💫 Create a modified babel preset based on an an existing preset.
JavaScript
85
star
50

preact-without-babel

🐎 How to use Preact in (native) ES2015, without Babel or JSX.
JavaScript
79
star
51

preact-shadow-root

🕴 Render a Preact subtree into the Shadow DOM.
JavaScript
72
star
52

linkref

Like Linked State, but for Refs. Works with Preact and React.
JavaScript
61
star
53

preact-css-transition-group

Apply CSS transitions when adding or removing Preact components/elements
JavaScript
61
star
54

proptypes

💂‍♂️ React's PropTypes, as a standalone module.
JavaScript
59
star
55

preact-token-input

🔖 A text field that tokenizes input, for things like tags.
JavaScript
59
star
56

nectarine

🍑 A mobile web / Android app for Peach! (peach.cool) ⚡
JavaScript
59
star
57

unified-element-properties-proposal

Unified Element Properties for the DOM
58
star
58

preact-jsx-chai

✅ Add JSX assertions to Chai, with support for Preact Components.
JavaScript
56
star
59

preact-compat-example

🚤 Demo of preact-compat + react-toolbox to reduce build size by 95%.
JavaScript
52
star
60

preact-transition-group

transition-group ui component for preact
JavaScript
51
star
61

scroll-list

📜 An infinitely scrollable list/datagrid. Handles millions of rows.
JavaScript
48
star
62

preact-in-es3

🐴 How to use Preact without Babel, ES2015 or JSX.
JavaScript
46
star
63

rollup-plugin-preserve-shebang

Rollup plugin to automatically preserve shebangs in entry modules.
JavaScript
45
star
64

preact-cli-plugin-async

Preact CLI plugin that adds converts async/await to Promises.
JavaScript
44
star
65

preact-views

📺 Named views for Preact, with easy-as-pie linking between them.
JavaScript
39
star
66

preact-richtextarea

📰 A text field that supports HTML editing. 📝
JavaScript
39
star
67

react-router-4-test

Did you know you can use React Router with Preact, no -compat?
JavaScript
35
star
68

element-worklet

34
star
69

documentation-viewer

📜 Hosted viewer for documentation.js JSON output.
JavaScript
34
star
70

sleeper

😴 REST abstraction so easy you could use it with your eyes closed. 💤
JavaScript
30
star
71

neatime

Returns a simple relative time string.
JavaScript
30
star
72

babel-preset-preact

Babel preset to transform JSX into h() calls
JavaScript
30
star
73

ama

Ask me stuff
28
star
74

htmlParser

Simple JavaScript HTML parser.
JavaScript
27
star
75

precharts

Just Recharts pre-aliased for Preact.
JavaScript
27
star
76

object-shape

Get a description of a JS object's shape.
JavaScript
24
star
77

eslint-config-developit

developit's generic eslint config for libraries
JavaScript
21
star
78

peach.cool

🍑 JavaScript library for Peach (peach.cool) ⚡
JavaScript
21
star
79

progress-spinner

⌚ A simple, CSS-only indeterminate spinner custom element.
HTML
21
star
80

rollup-plugin-postprocess

🎞 Find & replace postprocessing for Rollup output
JavaScript
18
star
81

desky

18
star
82

jasonformat.com

My blog
JavaScript
18
star
83

preact-tap-event-plugin

☝️ onTouchTap for preact
JavaScript
17
star
84

preact-svg

[DEPRECATED] 🎨 Use inline <svg> in Preact 4 and prior. 🌷
JavaScript
16
star
85

preact-styled-jsx-demo

Preact + styled-jsx = 💞
JavaScript
16
star
86

preact-vite-template

JavaScript
15
star
87

espz

JavaScript
13
star
88

hazelnut

🌰 Tiny inline AMD registry.
JavaScript
12
star
89

request-easy-cache

🐎 A simple, configurable & instantiable caching wrapper around request.
JavaScript
11
star
90

puredom

💲 Fast, chainable and exstensible JavaScript library for building web applications.
JavaScript
11
star
91

templeton

💪 Templating like the other ones, but not at all like the other ones.
JavaScript
10
star
92

bamboo-status-svg

A web service that generates build badges for Bamboo plans.
JavaScript
9
star
93

ford.js

👔 The library nobody wants but that is for some reason still mayor.
JavaScript
8
star
94

jasonp

An itty bitty JSONP module
JavaScript
7
star
95

browser-nativefs

Native File System API with legacy fallback in the browser
JavaScript
7
star
96

strip-dom-whitespace

Traverses the DOM to strip whitespace-only Text nodes
JavaScript
6
star
97

picomarkdown

Converts basic markdown to HTML.
JavaScript
6
star
98

babel-preset-es2015-minimal

💄 Babel's es2015 preset in loose mode without frills.
JavaScript
5
star
99

esbench

ESBench Feedback (future public repo)
4
star
100

babel-preset-es2015-minimal-rollup

Babel es2015 preset in loose mode without frills, made for Rollup.
JavaScript
4
star