title |
---|
Plugins |
A Rollup plugin is an object with one or more of the properties and hooks described below, and which follows our conventions. A plugin should be distributed as a packages which exports a function that can be called with plugin specific options and returns such an object.
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. For an example on how to use them, see Using plugins.
A List of Plugins may be found at https://github.com/rollup/awesome. If you would like to make a suggestion for a plugin, please submit a Pull Request.
The following plugin will intercept any imports of virtual-module
without accessing the file system. This is for instance necessary if you want to use Rollup in a browser. It can even be used to replace entry points as shown in the example.
// rollup-plugin-my-example.js
export default function myExample () {
return {
name: 'my-example', // this name will show up in warnings and errors
resolveId ( importee ) {
if (importee === 'virtual-module') {
return importee; // this signals that rollup should not ask other plugins or check the file system to find this id
}
return null; // other ids should be handled as usually
},
load ( id ) {
if (id === 'virtual-module') {
return 'export default "This is virtual!"'; // the source code for "virtual-module"
}
return null; // other ids should be handled as usually
}
};
}
// rollup.config.js
import myExample from './rollup-plugin-my-example.js';
export default ({
input: 'virtual-module', // resolved by our plugin
plugins: [myExample()],
output: [{
file: 'bundle.js',
format: 'esm'
}]
});
- Plugins should have a clear name with
rollup-plugin-
prefix. - Include
rollup-plugin
keyword inpackage.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.
Type: string
The name of the plugin, for use in error messages and warnings.
In addition to properties defining the identity of your plugin, you may also specify properties that correspond to available build hooks. Hooks can affect how a build is run, provide information about a build, or modify a build once complete.
Type: string | (() => string | Promise<string>)
Cf. output.banner/output.footer
.
Type: (error?: Error) => void | Promise<void>
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.
Type: (options: InputOptions) => void | Promise<void>
Called on each rollup.rollup
build.
Type: string | (() => string | Promise<string>)
Cf. output.banner/output.footer
.
Type: (options: OutputOptions, bundle: { [fileName: string]: AssetInfo | ChunkInfo }, isWrite: boolean) => void | Promise<void>
Called at the end of bundle.generate()
or bundle.write()
. bundle
provides the full list of files being written or generated along with their details:
// AssetInfo
{
fileName: string,
isAsset: true,
source: string | Buffer
}
// ChunkInfo
{
dynamicImports: string[],
exports: string[],
facadeModuleId: string | null,
fileName: string,
imports: string[],
isDynamicEntry: boolean,
isEntry: boolean,
modules: {
[id: string]: {
renderedExports: string[],
removedExports: string[],
renderedLength: number,
originalLength: number
},
},
name: string
}
Type: string | (() => string | Promise<string>)
Cf. output.intro/output.outro
.
Type: (id: string) => string | null | { code: string, map?: string | SourceMap } | Promise<...>
Defines a custom loader. Returning null
defers to other load
functions (and eventually the default behavior of loading from the file system).
Type: (options: InputOptions) => InputOptions | null
Reads and replaces or manipulates the options object passed to rollup.rollup
. Returning null
does not replace anything. This is the only hook that does not have access to most plugin context utility functions as it is run before rollup is fully configured.
Type: string | (() => string | Promise<string>)
Cf. output.intro/output.outro
.
Type: (code: string, chunk: ChunkInfo, options: OutputOptions) => string | { code: string, map: SourceMap } | null | Promise<...>
Can be used to transform individual chunks. Called for each Rollup output chunk file. Returning null
will apply no transformations.
Type: (error: Error) => void | Promise<void>
Called when rollup encounters an error during bundle.generate()
or bundle.write()
. The error is passed to this hook. To get notified when generation completes successfully, use the generateBundle
hook.
Type: () => void | Promise<void>
Called initially each time bundle.generate()
or bundle.write()
is called. To get notified when generation has completed, use the generateBundle
and renderError
hooks.
Type: (specifier: string | ESTree.Node, importer: string) => string | false | null | Promise<...>
Defines a custom resolver for dynamic imports. In case a dynamic import is not passed a string as argument, this hook gets access to the raw AST nodes to analyze. Returning null
will defer to other resolvers and eventually to resolveId
if this is possible; returning false
signals that the import should be kept as it is and not be passed to other resolvers thus making it external. Note that the return value of this hook will not be passed to resolveId
afterwards; if you need access to the static resolution algorithm, you can use this.resolveId(importee, importer)
on the plugin context.
Type: (importee: string, importer: string) => string | false | null | Promise<...>
Defines a custom resolver. A resolver loader can be useful for e.g. locating third-party dependencies. Returning null
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.
Type: (code: string, id: string) => string | { code: string, map?: string | SourceMap, ast? : ESTree.Program } | null | Promise<...>
Can be used to transform individual modules.
Type: (id: string) => void
Notifies a plugin whenever rollup has detected a change to a monitored file in --watch
mode.
☢️ These hooks have been deprecated and may be removed in a future Rollup version.
-
ongenerate
- UsegenerateBundle
- Function hook called whenbundle.generate()
is being executed. -
onwrite
- UsegenerateBundle
- Function hook called whenbundle.write()
is being executed, after the file has been written to disk. -
transformBundle
– UserenderChunk
- A( source, { format } ) => code
or( source, { format } ) => { code, map }
bundle transformer function. -
transformChunk
– UserenderChunk
- A( source, outputOptions, chunk ) => code | { code, map}
chunk transformer function.
More properties may be supported in future, as and when they prove necessary.
A number of utility functions and informational bits can be accessed from within most hooks via this
:
Emits a custom file to include in the build 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.
Structurally equivalent to this.warn
, except that it will also abort the bundling process.
Get the file name of an asset, according to the assetFileNames
output option pattern.
Returns additional information about the module in question in the form
{
id, // the id of the module, for convenience
isExternal, // for external modules that are not included in the graph
importedIds // the module ids imported by this module
}
If the module id cannot be found, an error is thrown.
Determine if a given module ID is external.
An Object
containing potentially useful Rollup metadata. meta
is the only context property accessible from the options
hook.
An Iterator
that gives access to all module ids in the current graph. It can be iterated via
for (const moduleId of this.moduleIds) { /* ... */ }
or converted into an Array via Array.from(this.moduleIds)
.
Use Rollup's internal acorn instance to parse code to an AST.
Resolve imports to module ids (i.e. file names). Uses the same hooks as Rollup itself.
Set the deferred source of an asset.
Using this method will queue warnings for a build. These warnings will be printed by the CLI just like internally-generated warnings (except with the plugin name), or captured by custom onwarn
handlers.
The warning
argument can be a string
or an object with (at minimum) a message
property:
this.warn( 'hmm...' );
// is equivalent to
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 a plugin
property containing the plugin name, code
(PLUGIN_WARNING
) and id
(the file being transformed) properties.
The position
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).
To reference an asset URL reference from within JS code, use the import.meta.ROLLUP_ASSET_URL_[assetId]
replacement. The following example 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.
load (id) {
const assetId = this.emitAsset('style.css', fs.readFileSync(path.resolve(assets, 'style.css')));
return `export default import.meta.ROLLUP_ASSET_URL_${assetId}`;
}
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.
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.
The transform
hook, if returning an object, can also include an ast
property. 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.)
(Use rollup-pluginutils for commonly needed functions, and to implement a transformer in the recommended manner.)
import { createFilter } from 'rollup-pluginutils';
export default function myPlugin ( options = {} ) {
const 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 submit it to https://github.com/rollup/awesome!