Rollup Tutorial For Beginners 2019

Rollup Overview

Rollup Tutorial from Coding compiler. Rollup is a JavaScript module wrapper that compiles small pieces of code into large chunks of complex code, such as a library or application. Rollup uses a new standardized format for code modules, which are included in the ES6 version of JavaScript, rather than previous special solutions such as CommonJS and AMD.

The ES6 module gives you the freedom and seamless use of the most useful stand-alone functions in your favorite library, and your project doesn’t have to carry other unused code. The ES6 module will eventually be natively implemented by the browser, but current Rollup can give you an early experience.

Rollup Quick Start Guide

Use npm install –global rollup the installation. Rollup can be invoked via the command line interface with an optional configuration file, or it can be called via the JavaScript API . Run rollup –help can view the available options and parameters.

See the sample class libraries and application projects that use Rollup in rollup-starter-lib and rollup-starter-app .

These commands assume that the name of the application entry start is main.js, and that you want all import dependencies (all imports) to be compiled into a single file called bundle.js.

For the browser:

# compile to a <script> containing a self-executing function ('iife')
$ rollup main.js --o bundle.js --f iife

For Node.js:

# compile to a CommonJS module ('cjs')
$ rollup main.js --o bundle.js --f cjs

For browsers and Node.js:

# UMD format requires a bundle name
$ rollup main.js --o bundle.js -f umd --name "myBundle"

Why Rollup?

If you split the project into small separate files, developing software is usually straightforward because it usually eliminates unforeseen interactions and significantly reduces the complexity of the problem you are trying to solve (complexity) Of the problem), and small projects ( not necessarily standard answers ) can be written succinctly at the beginning of the project . Unfortunately, JavaScript has not used this feature as a core feature of the language.

Tree-shaking

In addition to using the ES6 module, Rollup also statically analyzes the import in the code and will exclude any code that is not actually used. This allows you to architect your existing tools and modules without adding extra dependencies or bloating your project.

For example, when using CommonJS, you must import the complete tool or library object .

// Import a full utils object using CommonJS
var utils = require( 'utils' );
var query = 'Rollup';
// Use the ajax method of the utils object
utils.ajax( 'https://api.example.com?search=' + query ).then( handleResponse );

However, the use ES6 module, without having to import the entire utils object, we can only import (import) we need ajax a function:

// Import ajax function using the ES6 import statement
import { ajax } from 'utils';
var query = 'Rollup';
// Calling ajax function
ajax( 'https://api.example.com?search=' + query ).then( handleResponse );

Because Rollup only introduces the most basic and streamlined code, it can generate lightweight, fast, and low-complexity libraries and applications. Because this based on explicit import and export fashion statements, it is far “in output in the compiled code, simply run variable automatic detection minifier unused” more effective.

Rollup Compatibility

Import CommonJS

Rollup can import existing CommonJS modules through plugins .

Publish ES6 Modules

To make sure your ES6 module directly with the “run (such as Node.js and webpack) of the tool (tool) in CommonJS” use, you can use the Rollup compiled into CommonJS or UMD format, and then in package.json the file main points to the current compilation properties version of. If you package.json have a module field like Rollup and webpack 2 such ES6 awareness tools (ES6-aware tools) will directly import ES6 module version .

Common Problems

Why are ES modules better than CommonJS modules?

The ES module is the official standard and a clear development direction for the JavaScript language, and the CommonJS module is a special traditional format that is a temporary solution before the ES module is proposed.The ES module allows for static analysis to achieve optimizations like tree-shaking and provides advanced features such as circular references and dynamic binding.

What is ‘tree-shaking’?

Tree-shaking, also known as “live code inclusion,” is a process of clearing code that is not actually used in a given project, but it can be more efficient. Glossary source view: similar to clearing useless code

How do I use Rollup in a CommonJS module? (How do I use Rollup in Node.js with CommonJS modules?)

Rollup strives to implement the specification of the ES module, not necessarily require()the features of Node.js, npm, , and CommonJS. Therefore, loading the CommonJS module and using the Node module location resolution logic are implemented as optional plugins, which are not by default in the Rollup kernel. You only need to perform npm install the installation CommonJS and node-resolve plug-in and use the rollup.config.js configuration file to enable them, then you’re all set.

Is Rollup used to build libraries or applications? (Is Rollup meant for building libraries or applications?)

Rollup has been used by many major JavaScript libraries and can be used to build most applications. However, Rollup does not support some specific advanced features, especially when building some applications, especially the dynamic import of runtimes for code splitting and runtime . If you need these features more in your project, then Using Webpack may be more in line with your needs.

Who made the Rollup logo. It’s so cute! (Who made the Rollup logo? It’s lovely.)

I know! It was made by Julian Lloyd .
null

Rollup Tutorial

Create the first bundle

Before you start, you need to install Node.js so that you can use npm ; you also need to know how to use command line .

The easiest way to use Rollup is through the Command Line Interface (or CLI). Install Rollup globally first (you’ll see how to install it in your project, it’s easier to package, but don’t worry about it now). Enter the following on the command line:

npm install rollup –global # or `npm i rollup -g` for short

Now you can run rollup commands. Try it~

rollup

Since no parameters were passed, Rollup printed out instructions for use. This is run rollup –help or rollup -h the same effect.

Let’s create a simple project:

mkdir -p my-rollup-project/src
cd my-rollup-project

First, we need an entrance . Paste the following code to the new file src/main.js in:

// src/main.js
import foo from './foo.js';
export default function () {
 console.log(foo);
}

After you create an entry file referenced foo.js modules:

// src/foo.js
export default 'hello world!';

Now you can create a bundle:

rollup src/main.js -f cjs

-fThe option ( –output.format short for) specifies the type of bundle created – here is CommonJS (running in Node.js). Since no output file is specified, it will be directly printed stdout in:’use strict’;

var foo = 'hello world!';

var main = function () {
 console.log(foo);
};

module.exports = main;

You can also save the bundle as a file as follows:

rollup src/main.js -o bundle.js -f cjs

(You can also use it rollup src/main.js -f cjs > bundle.js, but as we will see later, this method is not very flexible when generating sourcemaps.)

Try running the following code:

node
> var myBundle = require('./bundle.js');
> myBundle();
'hello world!'

Congratulations, you have completed the first bundle with Rollup.

Using configuration files (Using config files)

The above method is not bad, but if you add more options, this way of command line is cumbersome.

To do this, we can create a configuration file to include the required options. The configuration file is written in JavaScript and is more flexible than the CLI.

Create a project named in rollup.config.js the file, add the following code:

// rollup.config.js
export default {
 input: 'src/main.js',
 output: {
   file: 'bundle.js',
   format: 'cjs'
 }
};

We use –config or -c to use the configuration file:

rm bundle.js # so we can check the command works!
rollup -c

The same command line options will override the options in the configuration file:

rollup -c -o bundle-2.js # `-o` is short for `--output.file`

(Note Rollup itself will deal with configuration files, you can use export default the syntax – the code will not compile similar tool through Babel and so on, we can only use the ES2015 Node.js version supports syntax used.)

If you prefer, you can also specify the default rollup.config.js file different profiles:rollup –config rollup.config.dev.js
rollup –config rollup.config.prod.js

Use plugins (Using plugins)

So far, we have created a simple file and a module into a simple bundle through a relative path. As you build more complex bundles, you often need more flexibility—introducing npm-installed modules, compiling code through Babel, working with JSON files, and more.

To this end, we can use plug-ins (plugins) to change the behavior of the key processes Rollup packaged in. The Rollup wiki maintains a list of available plugins.

In this tutorial, we will use rollup-plugin-json to have Rollup read data from a JSON file.

Install rollup-plugin-json as a development dependency:

npm install --save-dev rollup-plugin-json

(We use –save-devinstead –save, because they do not rely on this plugin when the code is actually executed – except when packaging)

Update src/main.js file, rather than from package.json src/foo.js read data:

// src/main.js
import { version } from '../package.json';

export default function () {
 console.log('version ' + version);
}

Edit rollup.config.js the file, adding JSON plug-ins:

// rollup.config.js
import json from 'rollup-plugin-json';

export default {
 input: 'src/main.js',
 output: {
   file: 'bundle.js',
   format: 'cjs'
 },
 plugins: [ json() ]
};
npm run build Execute Rollup. The results are as follows:
'use strict';

var version = "1.0.0";

var main = function () {
 console.log('version ' + version);
};

module.exports = main;

(Note that only the data that we actually need and dev Dependencies –name and other data package.json is ignored. This is a tree-shaking played a role.)

Command Line

We generally use Rollup on the command line. You can also provide a configuration file (with or without) to simplify command line operations while also enabling advanced features of Rollup.

Configuration files

Rollup’s configuration file is optional, but the use of configuration files is very powerful and convenient, so we recommend that you use

The configuration file is an ES6 module that exposes an object externally. This object contains some options that Rollup needs. Usually, we call this configuration file rollup.config.js, which is usually located in the root of the project.

Take a close look at this list of options for a large number of options , you can configure it to your profile as you need it.

// rollup.config.js
export default {
 // Core option
 input,    
 external,
 plugins,

 // Extra options
 onwarn,

 // danger zone
 acorn,
 context,
 moduleContext,
 legacy

 output: {  // Must (if you want to output more than one, can be an array)
   // Core option
   file,    
   format,
   name,
   globals,

   // Extra options
   paths,
   banner,
   footer,
   intro,
   outro,
   sourcemap,
   sourcemapFile,
   interop,

   // High risk option
   exports,
   amd,
   indent
   strict
 },
};

You must use a configuration file to do the following:

If you want to use the Rollup configuration file, remember to add –config or -c @@2 to the command line.

Command line flags

Many of the options in the configuration file are equivalent to the parameters of the command line. If you use the parameters here, the configuration file will be overwritten. For more information, check out the list of options for this package.

-i, --input                 The file to be packaged (required)
-o, --output.file           Output file (if there is no such parameter, it will be output directly to the console)
-f, --output.format [es]    Output file type (amd, cjs, es, iife, umd)
-e, --external              Exclude a comma-separated list of module IDs
-g, --globals               In the form of the `module ID:Global` key-value pair, separated by commas
                              Any definition of module ID definition added to external dependencies here

-n, --name                  Generate the name of the UMD module
-m, --sourcemap            Generation sourcemap (`-m inline` for inline map)
--amd.id                    The ID of the AMD module, the default is an anonymous function
--amd.define                Use Function instead of `define`
--no-strict                 Omitted in the generated package "use strict";`
--no-conflict               For UMD modules, generate a collision-free method for global variables
--intro                     Insert a piece of content at the very top of the inside of the block of the packaged file (inside the wrapper)
--outro                     Insert a piece of content at the bottom of the inside of the block of the packaged file (inside the wrapper)
--banner                    Insert a piece of content at the very top of the outside of the block of the packaged file (wrapper outside)
--footer                    Insert a piece of content at the very bottom of the outside of the block of the packaged file (wrapper outside)
--interop                   Contains public modules (this option is added by default)

In addition, the following parameters are also available:

-h/--help

Print a help document.

-v/--version

Print the installed Rollup version number.

-w/--watch

Monitor the source file for changes, if there are changes, repackage

--silent

Do not print warnings to the console.

JavaScript API

Rollup provides a JavaScript interface that can be used with Node.js. You can use it very rarely, and you’re likely to use the command line interface unless you want to extend the Rollup itself, or for some obscure tasks, such as generating a bundle of files with code.

Rollup.rollup

The rollup.rollup function returns a Promise, it resolves an bundle object, which has different properties and methods, as follows:

const rollup = require('rollup');

// see below for details on the options
const inputOptions = {...};
const outputOptions = {...};

async function build() {
 // create a bundle
 const bundle = await rollup.rollup(inputOptions);

 console.log(bundle.imports); // an array of external dependencies
 console.log(bundle.exports); // an array of names exported by the entry point
 console.log(bundle.modules); // an array of module objects

 // generate code and a sourcemap
 const { code, map } = await bundle.generate(outputOptions);

 // or write the bundle to disk
 await bundle.write(outputOptions);
}

build();

Input parameters (inputOptions)

inputOptions The object contains the following properties:

const inputOptions = {
 // Core parameter
 input, // Only required parameter
 external,
 plugins,

 // Advanced parameters
 onwarn,
 cache,

 // Risk parameter
 acorn,
 context,
 moduleContext,
 legacy
};

Output parameters (outputOptions)

outputOptions Objects include the following properties:

const outputOptions = {
 // Core parameter
 file,   // bundle.write is required
 format, // Required
 name,
 globals,

 // Advanced parameters
 paths,
 banner,
 footer,
 intro,
 outro,
 sourcemap,
 sourcemapFile,
 interop,

 // danger zone
 exports,
 amd,
 indent
 strict
};

Rollup.watch

Rollup also provides a rollup.watch function, when it detects a single disk module has been changed, it will rebuild your files beam. When you run the Rollup from the command line, and bring the –watchmark, this function will be used internally.

const rollup = require('rollup');

const watchOptions = {...};
const watcher = rollup.watch(watchOptions);

watcher.on('event', event => {
 // event.code Will be one of the following:
 //   START        — The listener is starting (restart)
 //   BUNDLE_START — Build a single file bundle
 //   BUNDLE_END   — Complete file bundle construction
 //   END        — Complete all file bundle builds
 //   ERROR        — Encountered an error while building
 //   FATAL        — Encountered an unrecoverable error
});

// Stop listening
watcher.close();

Listening parameters (watchOptions)

watchOptions The parameter is a configuration (or a configuration data) that you will export from a configuration file.

const watchOptions = {
 ...inputOptions,
 output: [outputOptions],
 watch: {
   chokidar,
   include,
   exclude
 }
};

View more documents to know more inputOptions and outputOptions details or query big list of options off chokidar, include and exclude data.

Rollup integrates with other tools

Npm packages

At some point, your project is likely to rely on node_modules packages installed from npm into your folder. Unlike other bundles like Webpack and Browserify, Rollup doesn’t know how to break the rules to handle these dependencies. – We need to add some configuration.

Let’s add a simple dependency on the answer , which outputs answers to life, the universe, and everything else.

npm install the-answer # or npm i the-answer

If we modify the src/main.js entrance file …

// src/main.js
import answer from 'the-answer';

export default function () {
 console.log('the answer is ' + answer);
}

…and then execute Rollup…

npm run build

…we will see the following warnings:

 (!) Unresolved dependencies
https://github.com/rollup/rollup/wiki/Troubleshooting#treating-module-as-external-dependency
the-answer (imported by main.js)

After the package bundle.js will still work in Node.js, as import declared transformed into CommonJS in the require statement, but the-answer it is not included in the package. Therefore, we need a plugin.

Rollup-plugin-node-resolve

This rollup-plugin-node-resolve plugin tells Rollup how to find external modules. Install it…

npm install --save-dev rollup-plugin-node-resolve

…add it to your profile:

// rollup.config.js
import resolve from 'rollup-plugin-node-resolve';

export default {
 input: 'src/main.js',
 output: {
   file: 'bundle.js',
   format: 'cjs'
 },
 plugins: [ resolve() ]
};

This time, when you run npm run build, there is no warning output – the package file bundle contains the referenced module.

Rollup-plugin-commonjs

Some libraries are exported to ES6 modules the-answer that you can import normally – just one such module.But for now, most of the packages in npm come in the form of CommonJS modules. Before they change, we need to convert the CommonJS module to ES2015 for Rollup processing.

This rollup-plugin-commonjs plugin is used to convert CommonJS to ES2015 modules.

Please note that rollup-plugin-commonjs should be used in other plug-ins to convert your module before – this is to prevent the destruction of other plug-ins CommonJS change detection.

Peer dependencies

Suppose you are building a library with peer dependencies, such as React or Lodash. If you set up external references as described above, your Rollup will package all the modules of imports together:

import answer from 'the-answer';
import _ from 'lodash';

You can fine tune which imports are intended to be packaged and which are external references (externals). For this example, we think it lodash is an external reference (externals), not a the-answer.

This is the configuration file:

// rollup.config.js
import resolve from 'rollup-plugin-node-resolve';

export default {
 input: 'src/main.js',
 output: {
   file: 'bundle.js',
   format: 'cjs'
 },
 plugins: [resolve({
   // Pass custom options to the parsing plugin
   customResolveOptions: {
     moduleDirectory: 'node_modules'
   }
 })],
 // Indicate which modules should be considered as external modules
 external: ['lodash']
};

In this way, “lodash” will now be treated as external (externals) and will not be packaged with your library.

External Accepts an array of module names or a function that accepts the name of the module, or returns true if it is treated as an external reference (externals). E.g:

export default {
 // ...
 external: id => /lodash/.test(id)
}

If you use [babel-plugin-lodash] ( https://github.com/lodash/babel-plugin-lodash) to optimally choose the lodash module, in this case, Babel will convert your import statement as follows,

import _merge from 'lodash/merge';

The “external” array form does not handle wildcards, so this import will only be treated as external dependencies/externals in the form of functions.

Babel

Many developers use [Babel] ( https://babeljs.io/ ) in their projects so they can use future versions of JavaScript features that are not supported by browsers and Node.js.

The easiest way to use Babel and Rollup is to use [rollup-plugin-babel] ( https://github.com/rollup/rollup-plugin-babel). Install it:

npm i -D rollup-plugin-babel

Add to the Rollup configuration file rollup.config.js:

// rollup.config.js
import resolve from 'rollup-plugin-node-resolve';
import babel from 'rollup-plugin-babel';

export default {
 input: 'src/main.js',
 output: {
   file: 'bundle.js',
   format: 'cjs'
 },
 plugins: [
   resolve(),
   babel({
     exclude: 'node_modules/**' // Only compile our source code
   })
 ]
};

Configuration is required before Babel actually compiles the code. Create a new file src/.babelrc:

{
 "presets": [
   ["latest", {
     "es2015": {
       "modules": false
     }
   }]
 ],
 "plugins": ["external-helpers"]
}

This setting has some unusual places. First, we set “modules”: false it up , otherwise Babel will convert our module to CommonJS before Rollup has the opportunity to do it, causing some of Rollup’s processing to fail.

Second, we use external-helpers plugins, which allow Rollup to reference “helpers” only once at the top of the package, rather than referencing it once in each module that uses them (this is the default behavior).

Third, we put the .babelrc files in the src middle, not the root directory. This allows us to have different.babelrc configurations for different tasks , such as testing, if we need it later – usually it would be better to configure it separately for a separate task.

Now, before we run the rollup, we need to install the latest preset and the external-helpers plugin

npm i -D babel-preset-latest babel-plugin-external-helpers

Running Rollup will now create a bundle package… In fact we are not using any of the ES2015 features. Let’s change it. Edit src / main.js:

// src/main.js
import answer from 'the-answer';

export default () => {
 console.log(`the answer is ${answer}`);
}

Run Rollup npm run build and check the packaged bundle:

'use strict';

var index = 42;

var main = (function () {
 console.log('the answer is ' + index);
});

module.exports = main;

Gulp

Rollup returns promises that gulp can understand, so integration is easy.

The syntax is very similar to the configuration file, but the properties are divided into two different operations, corresponding to the JavaScript API :

const gulp = require('gulp');
const rollup = require('rollup');
const rollupTypescript = require('rollup-plugin-typescript');

gulp.task('build', async function () {
 const bundle = await rollup.rollup({
   input: './src/main.ts',
   plugins: [
     rollupTypescript()
   ]
 });

 await bundle.write({
   file: './dist/library.js',
   format: 'umd',
   name: 'library',
   sourcemap: true
 });
});

ES Module Syntax

The following is intended to be a lightweight reference to the module behavior defined in the ES2015 specification , as proper understanding of import and export statements is critical to the successful use of Rollup.

Import

Imported values ​​cannot be reassigned, although imported objects and arrays can be modified (export modules, and any other imports, will be affected by this modification). In this case, they behave like const statements.

Named Imports

Import a specific item whose original name is imported from the source module.

import { something } from './module.js';

Import a specific item from the source module and specify a custom name when importing.

import { something as somethingElse } from './module.js';

Namespace Imports

Imports everything in the source module as an object, exposing the naming export of all source modules as properties and methods. The default export is excluded from this object.

import * as module from './module.js'

The above example of “something” will be attached to the import object as an attribute. “module.something”.

Default Import

Import default export of source files

import something from './module.js';

Empty Import

Load the module code, but don’t create any new objects.

import './module.js';

This is useful for polyfills, or when the main purpose of the imported code is related to the prototype.

Export

Named exports

Export previously declared values:

var something = true;
export { something };

Rename when exporting:

export { something as somethingElse };

Export immediately after the statement:

// This can be `var`, `let`, `const`, `class`, and `function` With the use of
export var something = true;

Default Export

Export a value as the default export for the source module:

export default something;

This is recommended only if the source module has only one export.

It is not good practice to combine default and named exports in the same module, although it is allowed by the specification.

How binding works

The ES module exports real-time bindings instead of values, so the values ​​can be changed after the initial import based on this example :


// incrementer.js
export let count = 0;

export function increment() {
 count += 1;
}


// main.js
import { count, increment } from './incrementer.js';

console.log(count); // 0
increment();
console.log(count); // 1

count += 1; // Error — Only incrementer.js can change this value.

Large list of options

Core functionality

Input (input -i/--input )

String This entry point packet (e.g.: Your main.js or app.js or index.js)

File (file -o/–output.file )

String The file to be written. Can also be used to generate sourcemaps, if applicable

Format (format -f/–output.format )

String Generate the format of the package. One of the following:

  • amd – Asynchronous module definition for module loaders like RequireJS
  • cjs – CommonJS for Node and Browserify/Webpack
  • es – Save the package as an ES module file
  • iife– An auto-executing function suitable as a <script>label. (If you want to create a bundle for your application, you might want to use it because it will make the file size smaller.)
  • umd- universal module defined in amd, cjs and iife as a whole

Generate package name (name -n/–name )

String The variable name, which stands for your iife/ umd package, can be accessed by other scripts on the same page.


// rollup.config.js
export default {
 ...,
 output: {
   file: 'bundle.js',
   format: 'iife',
   name: 'MyBundle'
 }
};

// -> var MyBundle = (function () {...

Plugins

Plug-in object Array (or a Plug-in Object) – For more information, please refer to the plug-in entry .Remember to call the imported plugin function (ie commonjs(), instead of commonjs).

// rollup.config.js
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';

export default {
 entry: 'main.js',
 plugins: [
   resolve(),
   commonjs()
 ]
};

External chain (external -e/–external )

Any two of a Function need for a idand returns true (external reference) or false (not external reference), or Array should be retained in the external bundle module ID references. The ID should be:

  1. Externally dependent name
  2. An ID of the path that has been found (like the absolute path of the file)
// rollup.config.js
import path from 'path';

export default {
 ...,
 external: [
   'some-externally-required-library',
   path.resolve( './src/some-local-file-that-should-not-be-bundled.js' )
 ]
};

When given as a command line argument, it should be a comma-separated list of IDs:

rollup -i src/main.js ... -e foo,bar,baz

Global module (globals -g/–globals )

Object In the form of id: name key-value pairs for umd/ iife package. For example: in such a case…

import $ from 'jquery';

… We want to tell Rollup jquery module id is equivalent to the $variable:

// rollup.config.js
export default {
 ...,
 format: 'iife',
 moduleName: 'MyBundle',
 globals: {
   jquery: '$'
 }
};

/*

var MyBundle = (function ($) {
 // Code here
}(window.jQuery));
*/

Alternatively, provide the ability to convert an external module ID to a global module.

When given as a command line argument, it should be a comma-separated list of “id:name” key-value pairs:

rollup -i src/main.js ... -g jquery:$,underscore:_

Advanced functionality

Path

Function, it gets an ID and returns a path, or id:path right Object. In the provided location, these paths will be used for the generated package instead of the module ID, allowing you to load dependencies, for example, from the CDN:

// app.js
import { selectAll } from 'd3';
selectAll('p').style('color', 'purple');
// ...

// rollup.config.js
export default {
 input: 'app.js',
 external: ['d3'],
 output: {
   file: 'bundle.js',
   format: 'amd',
   paths: {
     d3: 'https://d3js.org/d3.v4.min'
   }
 }
};

// bundle.js
define(['https://d3js.org/d3.v4.min'], function (d3) {

 d3.selectAll('p').style('color', 'purple');
 // ...

});

Banner/footer

String The string is prepended/appended to the bundle. (Note: the “banner” and “footer” options don’t break sourcemaps)

// rollup.config.js
export default {
 ...,
 banner: '/* my-library version ' + version + ' */',
 footer: '/* follow me on Twitter! @rich_harris */'
};

Intro/outro

String Similar banner and footer, in addition to the code inside any particular format wrapper.

export default {
 ...,
 intro: 'var ENVIRONMENT = "production";'
};

Cache

Object A previously generated package. Use it to speed up subsequent builds – Rollup will only reanalyze modules that have changed.

Onwarn

Function The warning message will be blocked. If not provided, the warning will be copied and printed to the console.

There is at least a warning code and message properties of objects, which means you can control how to handle different types of alerts:

onwarn (warning) {
 // Skip some warnings
 if (warning.code === 'UNUSED_EXTERNAL_IMPORT') return;

 // Throw an exception
 if (warning.code === 'NON_EXISTENT_EXPORT') throw new Error(warning.message);

 // Console prints everything warning
 console.warn(warning.message);
}

Many warnings also have a loc property and one frame that you can target to the source of the warning:

onwarn ({ loc, frame, message }) {
 // Print location (if applicable)
 if (loc) {
   console.warn(`${loc.file} (${loc.line}:${loc.column}) ${message}`);
   if (frame) console.warn(frame);
 } else {
   console.warn(message);
 }
}
Sourcemap -m/--sourcemap

If so true, a separate sourcemap file will be created. If so inline, the sourcemap will be appended to the generated output file as a data URI .

sourcemapFile

String The location of the generated package. If this is an absolute path, all source code paths in the sourcemap will be relative to it. map.fileThe attribute is sourcemapFile the base name (basename) because the location of the sourcemap is assumed to be adjacent to the bundle

If specified output, it sourcemapFile is not required, in which case the output file name will be inferred by adding a “.map” suffix to the bundle output file.

Interop

Boolean Whether to add ‘interop block’. By default ( interop:true), for security reasons, if you need to distinguish between default and named exports, Rollup will export any external dependencies “default” to a single variable. This usually only applies to your external dependencies (for example with Babel) (if you are sure you don’t need it), you can use “interop:false” to save a few bytes.

Danger zone

You may not need to use these options unless you know what you are doing!

Treeshake

Whether to apply tree-shaking. It is recommended that you omit this option (default is treeshake:true) unless you find a bug caused by the tree-shaking algorithm, in which case use “treeshake:false” once you have submitted the question!

Acorn

Any options that should be passed to Acorn, for example allowReserved:true.

Context

By default, the context of the module – this the value of the top level undefined. In rare cases, you may need to change it to something else, such as ‘window’.

moduleContext

And options.context the same, but each module may be id: context subject to, and may be a id => contextfunction.

Legacy

In order to increase support for legacy environments such as IE8, by stripping out more modern code that may not work properly, the cost is a departure from the precise specifications required for the ES6 module environment.

Exports

StringWhat export mode is used. By default auto, it entry guesses your intent based on what the module exports:

  • default- If you use export default …only export a thing, it is suitable to use this
  • named – If you export more than one thing, it is suitable to use this
  • none – If you don’t export anything (for example, you are building an application, not a library), then this is appropriate

Default And named the difference between affect how other people use the File bundle (bundle). If you use it default, CommonJS users can do this, for example

var yourLib = require( 'your-lib' );

Use named, the user can do this:

var yourMethod = require( 'your-lib' ).yourMethod;

A bit of a twist is if you use an named export, but there is also an default export, the user must do this to use the default export:

var yourMethod = require( 'your-lib' ).yourMethod;
var yourLib = require( 'your-lib' )['default'];

Amd –amd.idand–amd.define

Object Can contain the following attributes:

Amd.id is String used for the ID of the AMD/UMD package:

// rollup.config.js
export default {
 ...,
 format: 'amd',
 amd: {
   id: 'my-bundle'
 }
};

// -> define('my-bundle', ['dependency'], ...

Amd.define the String name of the function to use instead of define:

// rollup.config.js
export default {
 ...,
 format: 'amd',
 amd: {
   define: 'def'
 }
};

// -> def(['dependency'],...

Indent

String Is the indented string to use, for formats that need to be indented ( amd, iife, umd). Can also be false (no indentation) or true(default – auto indent)

// rollup.config.js
export default {
 ...,
 indent: false
};

Strict

True Or false (default true) – Whether to include ‘use strict’ pragma at the top of the generated non-ES6 package. Strictly speaking (geddit?), the ES6 module is always strictly mode, so you should have no good reason to disable it.

Watch options

Only use these options when you run the Rollup –watch signs or rollup.watch take effect.

Watch.chokidar

A Boolean value indicates you should use chokidar instead of the built-in fs.watchor a pass to the options object chokidar.

If you want to use it, you must install chokidar separately.

Watch.include

Limit file monitoring to certain files:

// rollup.config.js
export default {
 ...,
 watch: {
   include: 'src/**'
 }
}

Related JavaScript Tutorials For Beginners

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Reference and Specifications
Javascript Developer Console
Javascript Code editors
JavaScript Basics Tutorial
JavaScript Hello World.!
JavaScript Code Structure
External JavaScript Files

Leave a Comment