Plugins

Rasmus Porsager edited this page Aug 16, 2018 · 223 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

JS transpilation plugins

These plugins affect your Javascript code, cleaning it, ensuring legacy compatibility, or converting from other language to Javascript.

  • async - replaces async functions with generators for use in modern browsers or most versions of node.js
  • babel – transpile code with Babel
  • buble – transpile code with Bublé (like Babel but much faster)
  • bucklescript - compile Reason or OCaml code via bucklescript
  • cleanup – remove comments (conditionally), trim trailing spaces, compact empty lines, and normalize line endings to win/mac/unix in .js files.
  • coffee-react - convert .cjsx and .coffee to JS
  • coffee-script – convert CoffeeScript to JS
  • elm - compile Elm to JS
  • jspicl - transpile javascript into PICO-8 lua
  • markdown - import code from fenced code blocks in Markdown documents for lightweight literate programming
  • nodent - transpile ES2017 async/await with nodent
  • pegjs - import PEG.js grammars as parsers
  • purs - bundle PureScript modules
  • regenerator - provides transforming generator and async functions with ES5 Promise based functions
  • strip-code - remove parts of code based on regular expressions.
  • typescript - compile TypeScript just like JavaScript
  • typescript2 - compile TypeScript (2.0+) and have it not swallow errors

JS module plugins

These plugins control the behaviour of modules: dependencies, imports, exports, and where to look for external modules.

  • alias - define aliases when bundling packages
  • amd - convert AMD modules to ES6
  • async-define - Wraps an AMD bundle with async-define. The bundle will take care of being executed after its dependencies, even if they are loaded asynchronously.
  • bower-resolve – use the Bower resolution algorithm with Rollup
  • cjs-es - like commonjs but without proxy modules and reassignment tracking
  • commonjs – convert CommonJS modules to ES6
  • external-globals - replace imported bindings with a global variable.
  • force-binding - work between multi-entry and node-resolve to prevent duplicated imports inside bundles.
  • glob-import - Enables import X from './foo/*.js'
  • ignore - ignore modules by replacing them with an empty object
  • import-alias - Maps one import path to another. Allows referencing external imports as if they were internal.
  • includepaths – provide base paths to resolve imports from
  • inject – detect dependencies and inject them
  • legacy – add export declarations to legacy scripts that declare globals
  • named-directory - Provides shortcuts for colocated modules in directories
  • 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)
  • node-resolve-angular - Node module resolution with support for the "es2015" custom package field used by Angular 4+ to indicate ES2015-code-in-ES2015-modules.
  • paths - Let you use the same variables at different directory.
  • root-import - import modules by absolute path relative to entry
  • stub - stub module.exports at runtime
  • ts-paths – resolve modules from tsconfig paths in Rollup
  • virtual - load modules from memory
  • virtual-alias - alias dependencies using virtual modules.

Framework plugins

Plugins for working with some well-known JS frameworks

  • angular - angular2 template and styles inliner
  • jsx - compile React JSX and other JSX-like components
  • ractive – precompile Ractive components
  • riot - compile Riot.js tag file
  • svelte — compile Svelte components
  • vue - compile Vue components
  • vue2 - compile Vue 2.0 components

CSS & templating plugins

Plugins for importing CSS files or templates for templating engines.

  • collect-sass - import and collect sass files, then compile in a single context
  • css-only – output plain and simple CSS
  • css-porter - combine css import to a standalone css file
  • dustjs - import dustjs templates as modules
  • eft - import and compile .eft/.ef templates with ef.js automatically imported, with which you can use your components directly in your project
  • ejs - compile .ejs/.html templates, also load styles from <link>'ed css files and put them into <style> tags (usable for web components polyfilling)
  • embed-css - import .css as a list of classnames and append styling to outputs
  • jst - compile _.templates
  • less - import and compile less files
  • modular-css - alternative implementation of CSS Modules w/ rollup support
  • postcss - compile postcss and insert to head
  • posthtml - compile posthtml
  • posthtml-template - compile, import, & render posthtml templates as strings
  • 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)
  • reshape - compile, import, & render reshape templates as strings
  • sass - import and compile sass files
  • scss - import and compile multiple .scss, .sass and .css files
  • stylus-css-modules – compile Stylus and inject CSS modules
  • twig - import pre-compiled Twig.js templates
  • sass-variables - import scss/sass variables as javascript object

External file plugins

Plugins for importing external files (non-JS, non-CSS) as modules.

  • file-as-blob – import any (binary) file as a blob: URL
  • git-version - include the git branch and rev when doing import {version} from 'package.json'
  • glsl - import GLSL shaders as compressed strings into code
  • glslify - import GLSL strings with glslify (a node.js-style module system for GLSL)
  • gltf - import glTF 3d models as a uri or inlined json object
  • html - import html files as strings into code
  • hypothetical - import modules from an imaginary filesystem
  • image – import JPG, PNG, GIF and SVG images
  • inline-js - import static assets at build-time. Support transformers.
  • json – convert JSON to ES6
  • md - import and compile markdown files
  • memory - load entry from memory
  • shader - import GLSL shaders as strings
  • spritesmith — converts set of images into a spritesheet and SASS/LESS/Stylus mixins based on spritesmith
  • string – import text files as strings
  • svg-sprite — import SVG files and extract as external SVG sprite
  • svg-to-symbol - import SVG files as symbol strings
  • svgo - import & clean SVG files as strings
  • url – import any (binary) file as a data: URL or copies the asset to a destination folder
  • vue-inline-svg - import SVG files as Vue components
  • wasm — use WebAssembly in Rollup bundles
  • yaml – import data from YAML files

Text replacement

Plugins for replacing plain text in all kinds of text files.

  • ascii – rewrite non-ASCII characters in string literals
  • re – rollup replace plugin with RegExp supported
  • replace – replace occurrences of a set of strings

Linting & code QA

Plugins for helping with code quality, and to remove debug/test/assertion code when bundling.

  • analyzer - see what's bloating your bundle, treeshaking stats, and other metrics
  • eslint - verify entry and imported scripts
  • eslint-bundle - verify (and fix) bundled code with ESLint.
  • flow - remove Flow type annotations
  • flow-entry - make your library's Flow types available to users
  • istanbul – Instruments code for code coverage with Istanbul
  • sass-lint - verify imported scss files
  • strip – remove debugger statements and functions like console.log
  • stylint - verify entry stylus files
  • unassert - remove assertion calls via Unassert

Output & prettifying

These plugins control the final output of the bundle, or how Rollup looks like while it's bundling.

  • browsersync – serves your bundle via Browsersync
  • bundleutils - a set of functions commonly used after tree shaking, timestamp, singletons, unexport, babel and uglify
  • clear - clear the output directory
  • copy-assets - copies specified assets into your output directory
  • cpy - easily copy files and folders
  • delete - delete files and folders
  • espruino - send code to Espruino devices
  • filesize - show file size of the bundle in the cli
  • generate-html-template - generate html file with your bundle included, based on a template
  • generate-package-json - generate package.json file with packages from your bundle
  • google-closure-compiler - removes dead code and rewrites and minimizes what's left
  • gzip - create a compressed .gz artifact for your bundle
  • hash – generate output files with unique hashes
  • hashbang - preserve hashbang and make output file executable
  • license – add a license banner, including 3rd party licenses
  • livereload – refresh the page when your bundle changes
  • minify - just minify the bundle (es6 content)
  • prettier - run prettier on the final bundle
  • prettyuglify - minify generated bundle into the shape of an SVG's paths
  • progress - show current build progress
  • rebase - copies and adjusts asset references to new relative location in destination folder
  • serve – serve your bundle just like webpack-dev-server
  • shift-header - shift a "comment header" to the top of a bundle
  • uglify - minify & uglify generated bundle

Workflow plugins

Plugins for controlling the Rollup workflow itself.

  • auto-transform – applies Browserify transforms automatically based on a key in the package.json, just like Browserify does
  • browserify-transform – use Browserify transforms as plugins
  • conditional – Conditionally execute rollup plugins
  • execute - Execute shell command(s) sequentially when the bundle is generated.
  • graph – Generates module dependencies graph, using the DOT language
  • html-entry – allows to use <script>s in HTML files as 'entry points'
  • jscc – Conditional compilation (and declaration of ES6 imports) for rollup
  • make - Build dependency files suitable for make
  • multi-entry – allows multiple 'entry points' instead of just one
  • notify – display rollup errors as system notifications
  • sourcemaps – load external source maps from sourceMappingURLs
  • vinyl - import from Vinyl files
  • visualizer - visualize your bundle and analyze dependencies

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 ( inputOptions ) => options function that replaces or manipulates the options object passed to rollup.rollup. Returning null does not replace anything.

  • buildStart- a ( ) => void function that is called on each rollup.rollup build; you can also return a Promise.

  • buildEnd- a ( error ) => void function that is called when rollup has finished bundling, but before generate or write is called; you can also return a Promise. If an error occurred during the build, it is passed on to this hook.

  • resolveId – a custom ( importee, importer ) => id resolver (useful for e.g. locating third-party dependencies); you can also return a Promise. Returning null or undefined defers to other resolveId functions (and eventually the default resolution behavior); returning false signals that importee should be treated as an external module and not included in the bundle.

  • load – a custom ( id ) => code | { code, map } loader; you can also return a Promise. Returning null defers to other load functions (and eventually the default behavior of loading from the file system).

  • transform – a ( source, id ) => code | { code, map } module transformer function; you can also return a Promise.

  • transformChunk (formerly transformBundle) – a ( source, outputOptions, chunk ) => code | { code, map} chunk transformer function called for each Rollup output chunk file; you can also return a Promise. If you return null, no transformations will be applied.

  • generateBundle (formerly onwrite and ongenerate) - a ( outputOptions, bundle, isWrite ) => void function hook called when bundle.generate() or bundle.write() is being executed; you can also return a Promise. bundle provides the full list of files being written or generated along with their details.

  • intro – an intro text or a function for generating intro text; you can also return a Promise.

  • outro – an intro text or a function for generating outro text; you can also return a Promise.

  • banner – a string, or a function that returns a string; you can also return a Promise.

  • footer – a string, or a function that returns a string; you can also return a Promise.

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

Plugin context

From within all hooks, you can access a number of utility functions via this:

  • this.warn( warning [, position] ) - 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.

  • this.error( error [, position] ) - Equivalent to this.warn except that it will also abort the bundling process

  • this.resolveId(importee, importer) - Resolve imports to module ids (i.e. file names). Uses the same hooks as Rollup itself.

  • this.isExternal( id, parentId, isResolved ) - Determine if a given module ID is external.

  • this.parse( code, acornOptions ) - Use Rollup's internal acorn instance to parse code to an AST

  • this.emitAsset( assetName, source ) - Emits a custom file to include in the output, returning its assetId. You can defer setting the source if you provide it later via this.setAssetSource(assetId). A string or Buffer source must be set for each asset through either method or an error will be thrown on generate completion.

  • this.setAssetSource( assetId, source ) - Set the deferred source of an asset.

  • this.getAssetFileName( assetId ) - Get the file name of an asset, according to the assetFileNames output option pattern.

To reference an asset URL reference from within JS code, use the import.meta.ROLLUP_ASSET_URL_[assetId] replacement. For example:

load (id) {
  const assetId = this.emitAsset('style.css', fs.readFileSync(path.resolve(assets, 'style.css')));
  return `export default import.meta.ROLLUP_ASSET_URL_${assetId}`;
}

represents emitting a CSS file for a module that then exports a URL that is constructed to correctly point to the emitted file from the target runtime environment.

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 the transformation does not move code, you can preserve existing sourcemaps by returning null:

return {
  code: transformedCode,
  map: null
};

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

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.