Plugins

Rich Harris edited this page Jan 19, 2017 · 107 revisions

Plugins allow you to customise Rollup's behaviour by, for example, transpiling code before bundling, or finding third-party modules in your node_modules folder.

List of plugins

  • alias - define aliases when bundling packages
  • amd - convert AMD modules to ES6
  • angular - angular2 template and styles inliner
  • ascii – rewrite non-ASCII characters in string literals
  • async - replaces async functions with generators for use in modern browsers or most versions of node.js
  • auto-transform – applies Browserify transforms automatically based on a key in the package.json, just like Browserify does
  • babel – transpile code with Babel
  • bower-resolve – use the Bower resolution algorithm with Rollup
  • browserify-transform – use Browserify transforms as plugins
  • buble – transpile code with Bublé (like Babel but much faster)
  • cleanup – remove comments (conditionally), trim trailing spaces, compact empty lines, and normalize line endings to win/mac/unix in .js files.
  • coffee-script – convert CoffeeScript to JS
  • coffee-react - convert .cjsx and .coffee to JS
  • commonjs – convert CommonJS modules to ES6
  • conditional – Conditionally execute rollup plugins
  • css-only – output plain and simple CSS
  • eslint - verify entry and imported scripts
  • espruino - send code to Espruino devices
  • file-as-blob – import any (binary) file as a blob: URL
  • filesize - show file size of the bundle in the cli
  • flow - remove Flow type annotations
  • hypothetical - import modules from an imaginary filesystem
  • gzip - create a compressed .gz artifact for your bundle
  • hash – generate output files with unique hashes
  • html - import html files as strings into code
  • ignore - ignore modules by replacing them with an empty object
  • image – import JPG, PNG, GIF and SVG images
  • includepaths – provide base paths to resolve imports from
  • inject – detect dependencies and inject them
  • istanbul – Instruments code for code coverage with Istanbul
  • jscc – Conditional compilation (and declaration of ES6 imports) for rollup
  • json – convert JSON to ES6
  • jst - compile _.templates
  • jsx - compile React JSX and other JSX-like components
  • legacy – add export declarations to legacy scripts that declare globals
  • less - import and compile less files
  • license – add a license banner, including 3rd party licenses
  • livereload – refresh the page when your bundle changes
  • memory - load entry from memory
  • modular-css - alternative implementation of CSS Modules w/ rollup support
  • multi-entry – allows multiple 'entry points' instead of just one
  • md - import and compile markdown files
  • node-builtins - Allow to use Node.JS built-in packages with rollup
  • node-globals - injects the same node globals browserify does (i.e process, Buffer, etc)
  • node-resolve – use the Node.js module resolution algorithm (e.g. modules from node_modules, installed with npm)
  • pegjs - import PEG.js grammars as parsers
  • postcss - compile postcss and insert to head
  • progress - show current build progress
  • pug - transforms .pug templates in es6 modules with sourceMap support and runtime auto-import or static HTML strings.
  • pug-html - import Pug templates as HTML strings (converts to html at build time, unlike the above)
  • ractive – precompile Ractive components
  • re – rollup replace plugin with RegExp supported
  • rebase - copies and adjusts asset references to new relative location in destination folder
  • replace – replace occurrences of a set of strings
  • post-replace - replace occurrences of a set of strings after bundling
  • riot - compile Riot.js tag file
  • root-import - import modules by absolute path relative to entry
  • sass - import and compile sass files
  • scss - import and compile multiple .scss, .sass and .css files
  • serve – serve your bundle just like webpack-dev-server
  • sourcemaps – load external source maps from sourceMappingURLs
  • string – import text files as strings
  • strip – remove debugger statements and functions like console.log
  • stub - stub module.exports at runtime
  • stylus-css-modules – compile Stylus and inject CSS modules
  • typescript - compile TypeScript just like JavaScript
  • uglify - minify generated bundle
  • vinyl - import from Vinyl files
  • visualizer - visualize your bundle and analyze dependencies
  • vue - compile Vue components
  • vue2 - compile Vue 2.0 components
  • watch - support the rollup --watch command
  • yaml – import data from YAML files

Using plugins

Rollup accepts an array of plugins:

import { rollup } from 'rollup';
import nodeResolve from 'rollup-plugin-node-resolve';

rollup({
  entry: 'main.js',
  plugins: [ nodeResolve({ jsnext: true, main: true }) ]
}).then(...);

Consult each plugin's documentation for detailed documentation.

Creating plugins

Your plugin package should export a function that returns an object with one or more of the following properties:

  • name – the name of the plugin, for use in error messages and warnings
  • options – a function that replaces or manipulates the options object passed to rollup.rollup
  • load – a custom id => code loader. Returning null or undefined defers to other load functions (and eventually the default behavior of loading from the file system).
  • resolveId – a custom ( importee, importer ) => id resolver (useful for e.g. locating third-party dependencies). Returning null or undefined defers to other resolveId functions (and eventually the default resolution behavior); returning any other falsy value signals that importee should be treated as an external module and not included in the bundle.
  • transform – a source, id => code or source, id => { code, map } module transformer function
  • transformBundle – a ( source, { format } ) => code or ( source, { format } ) => { code, map } bundle transformer function
  • ongenerate - Function hook called when bundle.generate() is being executed. Receives .generate() options along with the underlying Bundle object.
  • onwrite - Function hook called when bundle.write() is being executed, after the file has been written to disk. Receives .write() options along with the underlying Bundle object.
  • intro – a function for generating intro text
  • outro – a function for generating outro text
  • banner – a string, or a function that returns a string
  • footer – a string, or a function that returns a string

More properties may be supported in future, as and when they prove necessary.

Warnings and errors

Inside a transform function, you can use this.warn(warning[, pos]) to provide feedback in a standard form.

The warning argument can be a string or a warning object with (at minimum) a message property:

// these are equivalent
this.warn( 'hmm...' );
this.warn({ message: 'hmm...' });

Use the second form if you need to add additional properties to your warning object.

Rollup will augment the warning object with plugin (the plugin name), code (PLUGIN_WARNING) and id (the file being transformed) properties.

The pos argument is a character index where the warning was raised. If present, Rollup will augment the warning object with pos, loc (a standard { file, line, column } object) and frame (a snippet of code showing the error).

These warnings will be printed by the CLI just like internally-generated warnings (except with the plugin name), or captured by custom onwarn handlers.

You can also use this.error(err[, pos]) in exactly the same way, the difference being that it will abort the bundling process.

Advanced loaders and transformers

The load hook can optionally return a { code, ast } object. The ast must be a standard ESTree AST with start and end properties for each node.

The transform hook, if returning an object, can also include an ast property. For an example of this see rollup-plugin-json which generates a 'fake AST' to speed up Rollup's handling of large JSON files.

Only use this feature if you know what you're doing. Note that only the last AST in a chain of transforms will be used (and if there are transforms, any ASTs generated by the load hook will be discarded for the transformed modules.)

Conventions

  • Plugins should have a clear name with rollup-plugin- prefix.
  • Include rollup-plugin keyword in package.json.
  • Plugins should be tested. We recommend mocha or ava which support promises out of the box.
  • Use asynchronous methods when it is possible.
  • Document your plugin in English.
  • Make sure your plugin outputs correct source mappings if appropriate.
  • If your plugin uses 'virtual modules' (e.g. for helper functions), prefix the module ID with \0. This prevents other plugins from trying to process it

Transformer plugins (i.e. those that return a transform function for e.g. transpiling non-JS files) should support options.include and options.exclude, both of which can be a minimatch pattern or an array of minimatch patterns. If options.include is omitted or of zero length, files should be included by default; otherwise they should only be included if the ID matches one of the patterns.

Use rollup-pluginutils to implement this:

import { createFilter } from 'rollup-pluginutils';

export default function myPlugin ( options = {} ) {
  var filter = createFilter( options.include, options.exclude );

  return {
    transform ( code, id ) {
      if ( !filter( id ) ) return;

      // proceed with the transformation...
      return {
        code: generatedCode,
        map: generatedSourceMap
      };
    }
  };
}

If a plugin transforms source code, it should generate a sourcemap automatically, unless there's a specific sourceMap: false option. Rollup only cares about the mappings property (everything else is handled automatically). If it doesn't make sense to generate a sourcemap (e.g. rollup-plugin-string, return an empty sourcemap:

return {
  code: transformedCode,
  map: { mappings: '' }
};

If you create a plugin that you think would be useful to others, please publish it to npm and add it to this page!