Git Product home page Git Product logo

microbundle's Introduction

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

microbundle's People

Contributors

andarist avatar andrewiggins avatar bors[bot] avatar developit avatar fezvrasta avatar forsakenharmony avatar freeman avatar g-plane avatar greenkeeper[bot] avatar gribnoysup avatar jovidecroock avatar jviide avatar katywings avatar kevlened avatar luisrudge avatar lukeed avatar luxp avatar maraisr avatar marcbouchenoire avatar marvinhagemeister avatar matiasolivera avatar msfragala avatar ngryman avatar preact-bot avatar realdennis avatar rschristian avatar tombyrer avatar tymondesigns avatar wardpeet avatar wcastand avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

microbundle's Issues

Windows globbing support

I'm using microbundle via unistore, and I can't get the commands with glob work.

$ microbundle src/integrations/*.js -o x.js -f cjs
Error: ENOENT: no such file or directory, open 'C:\Users\srph\Code\oss\unistore\src\integrations\*.js'

I reckon this has something to do with the globbing. Have yet to investigate. Putting this up here in case someone else might be experiencing the same thing.

OS: Windows 10
TTY: Git Bash (mintty 2.7.3)

Edit: Turns out that npm run build of this project itself neither works.

$ npm i
> [email protected] install C:\Users\srph\Code\oss\microbundle\node_modules\nodent-runtime
> node build.js

## Built C:\Users\srph\Code\oss\microbundle\node_modules\nodent-runtime/dist/index.js

> [email protected] 

Plans to add Typescript support?

Love the simplicity!

Do you have any plans to add Typescript support at some point?

maybe something like

microbundle --ts
// or
microbundle --transpile=typescript

Support for multiple "entries"

Having this implemented would resolve this issue.

The idea is that we need to output private package.json files to support appropriate es/cjs resolving, I believe that @kentcdodds got it "right" here. Although you might prefer having some convention for creating additional "entries" over additional config flag.

I will work on implementing this, hopefully some time soon~

TypeError: Object prototype may only be an Object or null: undefined

Hi,

Maybe I'm doing something wrong, but I'm writing a github-like markdown editor and I got into this issue.

TypeError: Object prototype may only be an Object or null: undefined

It happens if I try to include a 3rd party package. (using yarn link in my main folder and yarn link @webscopeio/react-markdown-editor in demo folder)
I'm sorry if I misunderstood something, I'm pretty new to bundling OSS React components. It's my first attempt.

Do you have any idea what am I doing wrong? I've been trying for hours :/

Code is available here https://github.com/webscopeio/react-markdown-editor

screen shot 2018-03-02 at 12 55 18

Proposal for serve command?

Heya! 🎉

First of all, yea.. it is not for apps (i think?), but it is possible to some extent. So we may include rollup-plugin-serve or *-server, and rollup-plugin-livereload.

Currently you can use watch and in another terminal to use some static serving tool, like wrapping micro(-dev) or directly us serve / budo. Budo is good enough and has livereload, but it bundles one more time unneccesary (cuz the trick is to budo dist/bundle.cjs.js --live). Also, you need to handle cleaning of dist and creating a index.html. So the scripts are something like that

{
  "scripts": {
    "index": "echo '<script src=\"./index.js\"></script>' > dist/index.html",
    "clean": "rm -rf dist",
    "predev": "yarn clean && mkdir dist && yarn index",
    "dev": "microbundle watch -f cjs --inline none",
    "server": "budo dist/index.js --live --port 5000"
  }
}

Object spread seems to be failing

Looks like buble supports it, as long as you pass an option for objectAssign: 'Object.assign' but in practice it doesn't seem to be working.

My code:

import { h } from 'preact'

export default ({ title, ...rest }) => (
  <div {...rest} className={`${rest.className}`} />
)

Output:

SyntaxError: Unexpected token (3:25) /some/path/page.js (nodent)
export default ({ title, ...rest }) => (
-------------------------^

Empty source map

.map file has empty sourse map
{"version":3,"file":"bundle.m.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;"}

used version 0.2.4

0.4.4 Could not find file error for Typescript

It looks like 0.4.4 did break some defaults for index.ts
Get Could not find file error

$ pwd                                                                                                                                                    
/Users/me/Dev/temp/sample
$ microbundle -v                                                                                                                                         
microbundle, 0.4.4
$ microbundle                                                                                                                                            
Error: Could not find file: '/Users/me/Dev/temp/sample/src/index.ts'.
$ ./node_modules/.bin/microbundle -v                                                                                                                     
microbundle, 0.4.3
$ ./node_modules/.bin/microbundle                                                                                                                        
Build output to dist:
      1.86 kB: sample.js
      1.86 kB: sample.esm.js
      1.92 kB: sample.umd.js
{
  "name": "sample",
  "version": "0.0.1",
  "main": "dist/sample.js",
  "jsnext:main": "dist/sample.esm.js",
  "module": "dist/sample.esm.js",
  "dev:main": "dist/sample.dev.js",
  "minified:main": "dist/sample.min.js",
  "devDependencies": {
    "microbundle": "0.4.3"
  }
}

File size much lower when using require vs import

Hello,

Im importin external npm package.
When im using const parse = require('form-parse'); my file size is much lower than using import parse from 'form-parse';

require =>
Wrote 884 B: index.umd.js
Wrote 818 B: index.js
Wrote 821 B: index.m.js

import =>
Wrote 2.6 kB: index.js
Wrote 2.65 kB: index.umd.js
Wrote 2.6 kB: index.m.js

Im writing a module for babel that converts to browser script.

Why size is so different and wich one should i use ?

Error: 'default' is not exported by ../node_modules/prop-types/index.js

I'm trying to compile a quite simple app.

// @flow
// index.js
import { h, render } from 'preact';
import App from './components/App.js';

const appElement = document.querySelector('#app');

appElement && render(<App />, appElement);
// components/App.js
// @flow
import { h } from 'preact';
import styled from 'preact-emotion';

const Container = styled('main')`
  color: red;
`;

export default function App() {
  return <Container>Red</Container>;
}

But I get:

Error: 'default' is not exported by ../node_modules/prop-types/index.js

This is my babelrc:

{
  "plugins": [["transform-react-jsx", { "pragma": "h" }], "emotion"]
}

It looks like the error happens when I import preact-emotion

add uglify `passes: 3` compress option for smaller bundle sizes

Recommend adding uglify passes: 3 compress option to:

microbundle/src/index.js

Lines 264 to 267 in dcf99c6

compress: {
keep_infinity: true,
pure_getters: true
},

for smaller bundle sizes.

Example:

$ bin/uglifyjs -V
uglify-es 3.3.9
$ cat example.js 
var o = {
    foo: 1,
    bar: 2,
    square: x => x * x,
    cube: x => x * x * x,
};
console.log(o.foo, o.cube(3));
$ cat example.js | bin/uglifyjs --toplevel -mc
var o=1,l=o=>o*o*o;console.log(o,l(3));
$ cat example.js | bin/uglifyjs --toplevel -mc passes=2
console.log(1,(o=>o*o*o)(3));
$ cat example.js | bin/uglifyjs --toplevel -mc passes=3
console.log(1,27);

Not compatible with webpack

So apparently webpack will follow the module property of package.json files over the main entry. Since microbundle uses this property to point to the un-processed source file, webpack will pull the raw source file whenever you try to import a microbundled package, entirely defeating the point of processing the file in the first place.

I'm not entirely sure what the right fix is for this - ultimately, you likely want webpack to pull the xxx.m.js version which has been processed by babel but is still using es modules, but this is impossible without breaking microbundle's entry point.

I guess my gut would be to use a different property for microbundle's entry point - happy to PR to help fix this if you have any suggestions.

--compress true - is it a good default?

IMHO it makes debugging harder, its not easy to look into source code of libraries in node_modules (built by microbundle) nor it is easy to debug microbundle itself because its built by itself with --compress true (default).

I guess the question is what is a primary goal & target of this tool? If producing micro libraries then I think files should be left unminified by default, minifying can be done later by subsequent tools - bundlers etc.

Throws an error if no name is set in package.json

The title probably says everything, but my problem was that I tried microbundle in a local package without a name field in the package.json file. This currently throws an internal error when replace is called on undefined (pkg.name).

I'd be happy to open a PR to fix this if you'd like, but I wasn't sure how you'd want to handle it (warn and exit? something else?).

Anyway, thanks for building this, it looks like a very useful tool!

Logo fix?

That slant tape is driving me insane 😅
Mind if I fix?
microfix_transparent

globals?

How can I define globals to avoid "....– treating it as an external dependency" msgs.

Nice work on microbundle!

Disable sourcemap option?

Probably unpopular opinion, but I don't always want sourcemaps to be produced. This is especially true when #66 takes shape.

This isn't a massive pain point or anything, so feel free to disregard~!

Reevaluate exports: 'auto'

It's just a request to evaluate if exports: 'auto' is still today the best solution. I understand its nice to use require('lib') instead of require('lib').default, but imho the BIG problem with having this auto mode by default is that whenever a user adds a named export from his/her library it is automatically a breaking change and one that might easily slip released as patch/minor because its really simple to miss that.

I'll make piece with either decision, just wanted to raise a concern about this.

I've filled this issue at rollup - rollup/rollup#1881 , but whatever they decide does not have to be the same for microbundle, hence "duplicated" issues.

default config for development mode

According your docs dev mode should be run via watch command. In this case I expect that bundle should not have minification (--compress=false). It's more conveniently to debug code by default.

Is it possible to change it to mentioned flag?

Including external library

I am trying to include a library at the top of my file via import 'wicg-inert and I get the following error? Is this not possible via microbundle?

screen shot 2018-01-24 at 12 53 28 pm

React component library

Does this support creating a react component library and importing a global stylesheet like import tailwindcss/dist/tailwind.min.css?

How to configure microbundle for a submodule structure

I have a structure very similar to lodash.

import module1 from 'project/module1'
import module1 from 'project/module2'
import module1 from 'project/module3'
...

My entry point looks like (index.js):

module.exports = {
    module1: require('./module1'),
    module2: require('./module2'),
}

Is it possible that microbundle creates a file for each module separately? Because I'm getting index.m.js and index.umd.js

Error: Unexpected token

Hey!

I'm getting the error "Error: Unexpected token" with this code:

class Base {}
export default () => {
  return class extends Base {};
};

If I change it to:

class Base {}
export default () => {
  class R extends Base {}
  return R;
};

...it then works. It seems the class extends run together is what's causing the problem. My intuition tells me that maybe this issue is down the tooling stack in Bublé or Nodent, possibly, but I didn't find any errors when running through them separately. I didn't have time to check Rollup or the Uglify plugin for it yet due to time constraints.

I could have missed something somewhere, though. Any help or guidance on this would be appreciated.

Behavior with scoped packages

Suppose I have

{
  "name": "@bebraw/schnitzel",
  "version": "0.0.0",
  "description": "",
  "main": "src",
  "scripts": {
    "build": "microbundle",
    "dev": "microbundle watch"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "devDependencies": {
    "microbundle": "^0.2.3"
  }
}

and src/index.js.

If I run npm run build, it generates src/@bebraw.

Is that expected?

Error with 'uglify' plugin

When run npm run build, I got this error:

Error: Error transforming bundle with 'uglify' plugin: Unexpected token: name (Screen$1)

Support JSX ?

Hi, i wonder if it's possible to use JSX in the source code.
This is a test repo : https://github.com/wcastand/test-microbundle
I have a small repo to test it out and right now i get an error from nodent :

▲ test-microbundle at master ✔ yarn build
yarn run v1.3.2
$ microbundle --jsx
SyntaxError: Unexpected token (4:2) /Users/willoo/Documents/Projects/test-microbundle/src/index.js (nodent)
  <div>
--^
✨  Done in 0.50s.

In the source code you have an options for jsx in buble options.jsx but nodent is before buble.

Formats?

How can I specify multiple formats? e.g. cjs and es. I thought I would so something like this:

microbundle src/*.js --format 'cjs,es'

But it doesn't work. I get this error:

$ microbundle src/*.js --formats 'cjs, es'
Error: Invalid format: cjs, es - valid options are amd, cjs, es, iife, umd

Any ideas?

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.

An in-range update of rollup is breaking the build 🚨

☝️ Greenkeeper’s updated Terms of Service will come into effect on April 6th, 2018.

Version 0.56.4 of rollup was just published.

Branch Build failing 🚨
Dependency rollup
Current Version 0.56.3
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

rollup is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • continuous-integration/travis-ci/push The Travis CI build failed Details

Commits

The new version differs by 38 commits.

  • 018bcd2 0.56.4
  • a7627e3 Merge branch 'release-0.56.4'
  • 58a6da4 Reset git on postcommit to fix a webstorm issue
  • 65dd2d1 Merge branch 'asmockler-prettier' into release-0.56.4
  • 77079db Merge branch 'system-form' into release-0.56.4
  • 53003b8 Merge branch 'lamby-reproducible-build' into release-0.56.4
  • 9291989 Merge branch 'reexport-tracing' into release-0.56.4
  • c3da6aa Merge branch 'chunk-import-variable-deduping' into release-0.56.4
  • e932f95 Merge branch 'throw-on-warnings' into release-0.56.4
  • 3f74e82 Merge branch 'system-default-formatting' into release-0.56.4
  • 8c56d63 Merge branch 'adrianheine-sourcemap' into release-0.56.4
  • dfc3280 0.56.3
  • 8865311 Make sure tests are only removed if they contain at most an "_actual" directory
  • fa7a618 Automatically remove directories of missing tests instead of throwing an error
  • ccd9d23 getModuleDeclarations refactoring

There are 38 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

I think there is a problem with rollup-plugin-uglify?

cc: @developit I think there is a problem with rollup-plugin-uglify

When I try to build my module this was comes up.

$ yarn microbundle
yarn run v1.1.0
$ microbundle build
Using named and default exports together. Consumers of your bundle will have to use jaysn['default'] to access
the default export, which may not be what you want. Use `exports: 'named'` to disable this warning
(node:4720) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Error transforming bundle with 'uglify' plugin: Unexpected token: name (StructError)
(node:4720) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Using named and default exports together. Consumers of your bundle will have to use jaysn['default'] to access
the default export, which may not be what you want. Use `exports: 'named'` to disable this warning
(node:4720) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Error transforming bundle with 'uglify' plugin: Unexpected token: name (StructError)
Error: Error transforming bundle with 'uglify' plugin: Unexpected token: name (StructError)
Done in 13.40s.

This repo I was try to build https://github.com/lowsprofile/jaysn

This is my package.json

{
  "name": "jaysn",
  "version": "0.1.3",
  "description": "Lightweight JSON database for Node, Hybrid, and browser.",
  "homepage": "https://lowsprofile.github.io/jaysn/",
  "repository": "lowsprofile/jaysn",
  "author": "Eries Trisnadi <[email protected]> (https://eries.id)",
  "license": "MIT",
  "keywords": [],
  "main": "dist/jaysn.js",
  "module": "dist/jaysn.es.js",
  "eslintConfig": {
    "parser": "babel-eslint",
    "extends": "airbnb-base"
  },
  "files": [
    "dist",
    "README.md",
    "LICENSE"
  ],
  "source": [
    "src/Jaysn.js"
  ],
  "dependencies": {
    "immutable": "~4.0.0-rc.9",
    "path": "^0.12.7",
    "superstruct": "^0.4.5"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-eslint": "^8.0.2",
    "babel-plugin-transform-es2015-destructuring": "^6.23.0",
    "babel-plugin-transform-es2015-function-name": "^6.24.1",
    "babel-plugin-transform-es2015-parameters": "^6.24.1",
    "babel-preset-es2015": "6.24.1",
    "babel-preset-es2015-rollup": "^3.0.0",
    "babel-preset-stage-1": "^6.24.1",
    "babel-register": "^6.26.0",
    "chai": "^4.1.2",
    "coveralls": "^3.0.0",
    "eslint": "^4.12.0",
    "eslint-config-airbnb-base": "^12.1.0",
    "eslint-config-prettier": "^2.9.0",
    "eslint-plugin-import": "^2.8.0",
    "eslint-plugin-prettier": "^2.4.0",
    "microbundle": "^0.2.4",
    "mocha": "^4.0.1",
    "mustache": "^2.3.0",
    "npm-run-all": "^4.1.2",
    "nyc": "^11.3.0",
    "prettier": "1.9.2",
    "rollup": "^0.52.0",
    "rollup-plugin-babel": "^3.0.2",
    "rollup-plugin-buble": "^0.18.0",
    "rollup-plugin-commonjs": "^8.2.6",
    "rollup-plugin-json": "^2.3.0",
    "rollup-plugin-node-resolve": "^3.0.0",
    "rollup-plugin-strip-banner": "^0.2.0",
    "rollup-plugin-uglify": "^2.0.1",
    "shx": "^0.2.2",
    "sinon": "^4.1.2",
    "uglify-es": "^3.2.0",
    "uglify-save-license": "^0.4.1"
  },
  "scripts": {
    "build": "run-s format build:*",
    "build:dist": "run-s clean:dist bundle format:dist",
    "build:docs": "run-s clean:docs mustache",
    "bundle": "run-s bundle:*",
    "bundle:cjs": "run-s \"rollup -c tools/build-cjs.js\"",
    "bundle:es": "run-s \"rollup -c tools/build-es.js\"",
    "format": "run-s \"lint --fix\"",
    "format:dist": "prettier --write \"dist/**/{jaysn.es.js,jaysn.js}\"",
    "clean:dist": "run-s \"rm -rf dist\"",
    "clean:docs": "run-s \"rm -rf docs\" \"mkdir docs\"",
    "coverage": "nyc report --reporter=text-lcov | coveralls",
    "lint": "eslint src test tools",
    "microbundle": "microbundle build",
    "mkdir": "shx mkdir",
    "mustache": "node tools/build-docs && shx cp -r resources/css docs && mustache -p resources/partials/menu.mustache -p resources/partials/content.mustache resources/docs.json resources/docs.mustache > docs/index.html",
    "prepublish": "run-s build",
    "rm": "shx rm",
    "rollup": "rollup",
    "test": "run-s -l lint \"test:mocha {@}\" test:cover --",
    "test:mocha": "mocha --require babel-register",
    "test:cover": "nyc --require babel-register mocha --timeout=3000"
  }
}

Add Vue.js support

I've recently built a Vue.js component for lazy loading images and wanted to use microbundle for its setup, but couldn't make it work.

What's required to have Vue.js support?

Wrong flag for strict mode

For adding strict mode we need to add --strict=true flag according the docs.
Expected result: use strict is inserted in the bundle.
Actual result: use strict is not inserted in the bundle.

Reasons: looks like in yargs https://github.com/yargs/yargs/blob/master/docs/api.md#optionkey-opt flag default value of the type flag is 'string' , so your check (options.strict===true) always return false

Possible solution: add type: "boolean", in yargs.option('strict', { // ...})
version: 0.2.4

TypeScript declaration files are not emitted

I tried the new TypeScript support in version 0.4.0 and it is awesome! Thank you!

However, I have a question regarding the declaration files. Shouldn't they be emitted as well?

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2015",
    "module": "commonjs",
    "declaration": true,
    "outDir": "dist"
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*-spec.ts"]
}

and the output in the dist folder contains all files (index.js, index.m.js, index.umd.js and respective map files) except index.d.ts. Any idea?

[Question] How to create UMD bundle includings dependencies

Hello,

I trying to generate an UMD bundle including all the dependencies necessary. This is the code:
https://github.com/microlinkhq/microlinkjs/blob/master/packages/microlinkjs/src/index.js

I'm running the following command:

❯ NODE_ENV=production npx microbundle build --target browser --entry lib/index.js --format es,cjs --inline all
Build output to lib:
      1.54 kB: index.js
      1.54 kB: index.m.js

But the filesize is too small, because it doesn't include all the code dependencies.

I'm trying with external:none or inline:all but looks like the code doesn't support it
https://github.com/developit/microbundle/blob/master/src/index.js#L152

How can I do that using microbundle?

Error: Unexpected character '#'

I'm unable to run the microbundle from master without getting the error above.

The last successful SHA is ff42a14 (just before the upgrade to [email protected])

Env:
macOS 10.13.2
node 8.9.4
npm 5.6.0

Repro:

git clone https://github.com/developit/dlv.git
cd dlv
npm i
npm i --save-dev developit/microbundle
npm run build

Test infrastructure

This tool need a test setup - for obvious reasons. I'd like to work on some features, but I'm totally not confident about making changes.

I'd like to work on this, but I'd like to establish what kind of tests should be written. I feel that snapshot testing might be a good for this - as primary testing solution. Additionally we could write some additional manual tests, but for a tool such as this such tests are often not obvious.

Beside setting up a testing infrastructure I'd appreciate coming up with good testing scenarios (especially for more convoluted options/combination of options etc) that I could not come up with without examinating the source code carefully.

Strange build output

I happened to hear about microbundle a day or so ago so I decided to try it on a tiny library I was hacking on. The output seems really weird, though:

function t(t){return new Proxy(t,{get:function(t,r){return r in t?t[r]:e.lookup(r)}})}var r=function(){this.reset()};r.prototype.register=function(t,r){this._registry.set(t,r)},r.prototype.lookup=function(t){return this._registry.get(t)},r.prototype.reset=function(){this._registry=new Map};var e=new r,n=function(){return t(this)};n.extend=function(r){return function(r){function e(){return r.call(this),t(this)}return r&&(e.__proto__=r),e.prototype=Object.create(r&&r.prototype),e.prototype.constructor=e,e}(r)},exports.registry=e,exports.RegistryAccess=n;
//# sourceMappingURL=index.js.map
kup(prop);
        }
    });
}

var RegistryAccess = function RegistryAccess() {
    return registerForAccess(this);
};
RegistryAccess.extend = function (Klass) {
    return (function (Klass) {
        function anonymous() {
            Klass.call(this);
            return registerForAccess(this);
        }

        if ( Klass ) anonymous.__proto__ = Klass;
        anonymous.prototype = Object.create( Klass && Klass.prototype );
        anonymous.prototype.constructor = anonymous;

        return anonymous;
    }(Klass));
};

export { registry, RegistryAccess };
//# sourceMappingURL=index.js.map

That's the contents of the dist/index.js file that is output. It doesn't even seem like valid JS syntax after the first sourceMappingURL comment.

You can clone and try it yourself here:

https://github.com/alexlafroscia/service-locator

How to consume different bundles from package.json

Hey,

I'm intereted in know how to define correctly each bundle at package.json.

For example, I know cjs bundle is the property main.

What happens with the rest? Could be a great resource to put into the readme 🙂

Build failed when using specific dependencies

Here is demo with reproduce.
I'm build my library that depends on multiple packages, that i want to be bundled with my lib.

https://github.com/KatSick/microbundle-mlr-issue

You need to run:

yarn
yarn build

and see error:

(node:11685) UnhandledPromiseRejectionWarning: Error: 'Component' is not exported by node_modules/react/index.js
    at error (/Users/ochervak/Projects/Self/microbundle-mlr-issue/node_modules/rollup/dist/rollup.js:170:15)
    at Module.error (/Users/ochervak/Projects/Self/microbundle-mlr-issue/node_modules/rollup/dist/rollup.js:17170:9)
    at missingExport (/Users/ochervak/Projects/Self/microbundle-mlr-issue/node_modules/rollup/dist/rollup.js:16843:12)
    at Module.trace (/Users/ochervak/Projects/Self/microbundle-mlr-issue/node_modules/rollup/dist/rollup.js:17253:17)
    at ModuleScope.findVariable (/Users/ochervak/Projects/Self/microbundle-mlr-issue/node_modules/rollup/dist/rollup.js:14344:28)
    at Node.Identifier.bindNode (/Users/ochervak/Projects/Self/microbundle-mlr-issue/node_modules/rollup/dist/rollup.js:11993:40)
    at NodeBase.bind (/Users/ochervak/Projects/Self/microbundle-mlr-issue/node_modules/rollup/dist/rollup.js:11007:14)
    at /Users/ochervak/Projects/Self/microbundle-mlr-issue/node_modules/rollup/dist/rollup.js:11013:56
    at /Users/ochervak/Projects/Self/microbundle-mlr-issue/node_modules/rollup/dist/rollup.js:11027:66
    at Array.forEach (<anonymous>)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.