preface
The project has been using Webpack, the previous paragraph needs to develop several class libraries for other platforms to use, originally planned to continue to use Webpack, but felt that webpack used to develop JS library, not only cumbersome and packaged file volume is relatively large. Vue is also packaged by rollup. This time I was developing the class library again, so I quickly started rollup.
This article is after I have a certain project practice, back to share with you how to quickly start rollup from zero.
What is therollup
?
What is rollup?
The official documentation for rollup is clear:
Rollup is a JavaScript module wrapper that compiles small pieces of code into large, complex pieces of code, such as libraries or applications.
Unlike Webpack’s orientation towards application packaging, rollup.js is more focused on Javascript library packaging.
Many well-known frameworks or libraries, such as Vue and React, are packaged with rollup.js.
Why is itrollup
?
Webpack I’m sure you’ve all used webPack, so why use rollup for some scenarios? Here’s a quick comparison between WebPack and rollup:
In general, Webpack and rollup can play their advantages in different scenarios. Webpack has “built-in advantages” for code splitting and static resource imports, and supports hot module replacement (HMR), which Rollup does not.
So webPack is preferred when developing applications, but Rollup has algorithmic advantage for tree-shaking code and ES6 modules. If your project only needs to be packaged in a simple bundle and is developed based on ES6 modules, use Rollup.
Webpack has supported tree-shaking since 2.0, and packaging of ES6 Modules is supported with Babel-Loader. In fact, Rollup has gradually lost its edge. However, it has not been abandoned. Instead, it is favored by many library developers due to its simple API and usage. React, Vue, etc., all use rollup as a build tool.
Quick learning
We’ll spend about ten minutes or so looking at the basics of rollup and completing a Hello World.
The installation
First install rollup globally:
npm i rollup -g
Copy the code
Directory Preparation (Hello World)
Next, we initialize a project directory as shown below
├ ─ ─ dist # compile results ├ ─ ─ example # HTML reference example │ └ ─ ─ index. The HTML ├ ─ ─ package. The json └ ─ ─ the SRC # source └ ─ ─ index, jsCopy the code
SRC /index.js: SRC /index.js
console.log("KeSen");
Copy the code
Then run the following command from the command line:
rollup src/index.js -f umd -o dist/bundle.js
Copy the code
We can generate bundle.js in the dist directory by executing the following command:
(function (factory) {
typeof define === 'function'&& define.amd ? define(factory) : factory(); } ((function () { 'use strict';
console.log("KeSen");
})));
Copy the code
At this time, we are again inexample/index.html
The package generated abovebundle.js
File, open browser:As we expected, the console outputKeSen
.
At this point, we’ve packaged a very simple demo with rollup.
If you don’t understand the parameters in the command line, let me explain them one by one:
-f
.-f
The parameter is--format
Which stands for the format of the generated code,amd
Said theAMD
Standard,cjs
forCommonJS
Standard,esm
(or es) isES
Module standards.-f
Can beamd
,cjs
,system
,esm
(‘es’ also works),iife
orumd
Any one of them.-o
.-o
The output path is specified. Here we output the packaged file todist
In the directorybundle.js
In addition to these two commands, there are a number of other common commands (I will briefly list the remaining two common ones, the full rollup command line arguments) :
-c
. The specifiedrollup
Configuration file.-w
. Listen for changes to the source file. If so, repackage it.
Using configuration files (rollup.config.js
)
Using the command line, it’s fine to have a few options, but it’s cumbersome to add more options.
To do this, we can create a configuration file to include the required options
Create a file called rollup.config.js in your project and add the following code:
export default {
input: ["./src/index.js"].output: {
file: "./dist/bundle.js".format: "umd".name: "experience",}};Copy the code
Then the command line executes:
rollup -c
Copy the code
Open the dist/bundle.js file and you’ll see the same result as the command line package above.
Here is a brief explanation of the configuration file options:
input
Represents the path to the entry file (old version is Entry, obsolete)output
Represents the contents of an output file, which allows an object or array to be passed in. When an array is passed in, multiple files in turn are output, which contains the following contents:output.file
: Path to the output file (the old version is dest and has been deprecated)output.format
: Format of the output fileoutput.banner
: Content added to the file headeroutput.footer
: The content added at the end of the file
At this point, you’re almost ready to rollup.
The advanced
However, this is not enough for a real business scenario.
Below, I’ll look at several commonly used plug-ins in Rollup, as well as the external attribute and tree-shaking mechanism.
resolve
The plug-in
Why use itresolve
The plug-in
In the introductory example above, the objects we package are local JS code and libraries, but in real development, it is unlikely that all libraries will be local and we will most likely download remote libraries via NPM.
Unlike other bundles like WebPack and Browserify, Rollup doesn’t know how to break the rules to handle these dependencies. So we need to add some configuration.
resolve
The plug-in USES
First add a dependency on the-Answer to our project, then modify the SRC /index.js file:
import answer from "the-answer";
export default function () {
console.log("the answer is " + answer);
}
Copy the code
Run NPM run build.
Json scripts: “build”: “rollup-c-w”
You get the following error:After packagingbundle.js
Will still be inNode.js
Butthe-answer
Not included in the package. To solve this problem, we merged the source code we wrote with the third-party libraries we relied on,rollup.js
Provides us withresolve
The plug-in.
First, install the Resolve plug-in:
npm i -D @rollup/plugin-node-resolve
Copy the code
Modify configuration file rollup.config.js:
import resolve from "@rollup/plugin-node-resolve";
export default {
input: ["./src/index.js"].output: {
file: "./dist/bundle.js".format: "umd".name: "experience",},plugins: [resolve()],
};
Copy the code
So let’s do it againnpm run build
Error no longer exists:
Open dist/bundle.js:
(function (global, factory) {
typeof exports= = ='object' && typeof module! = ='undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeofglobalThis ! = ='undefined' ? globalThis : global || self, global.experience = factory()); } (this, (function () { 'use strict';
var index = 42;
function index$1 () {
console.log("the answer is " + index);
}
return index$1;
})));
Copy the code
The bundle file bundle.js already contains the referenced modules.
In cases where we want some libraries to remain external references despite using the resolve plug-in, we need to use the external attribute to tell rollup.js which libraries are external.
External properties
Modify the rollup.js configuration file:
import resolve from "@rollup/plugin-node-resolve";
export default {
input: ["./src/index.js"].output: {
file: "./dist/bundle.js".format: "umd".name: "experience",},plugins: [resolve()],
external: ["the-answer"]};Copy the code
Repackage and open the dist/bundle.js file:
(function (global, factory) {
typeof exports= = ='object' && typeof module! = ='undefined' ? module.exports = factory(require('the-answer')) :
typeof define === 'function' && define.amd ? define(['the-answer'], factory) :
(global = typeofglobalThis ! = ='undefined' ? globalThis : global || self, global.experience = factory(global.answer)); } (this, (function (answer) { 'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var answer__default = /*#__PURE__*/_interopDefaultLegacy(answer);
function index () {
console.log("the answer is " + answer__default['default']);
}
return index;
})));
Copy the code
At this point we see that the-Answer has been introduced as an external library.
commonjs
The plug-in
Why is it neededcommonjs
The plug-in
By default, only ES6+ import/export is supported for modules in rollup.js compiled source code. However, a large number of NPM modules are based on CommonJS modules, which results in a large number of NPM modules cannot be compiled directly.
Hence the plugin that enables rollup.js to compile NPM modules and CommonJS modules: @rollup/plugin-commonjs.
commonjs
The plug-in USES
First, install the module:
npm i -D @rollup/plugin-commonjs
Copy the code
Then modify the rollup.config.js file:
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
export default {
input: ["./src/index.js"],
output: {
file: "./dist/bundle.js",
format: "umd",
name: "experience",
},
plugins: [resolve(), commonjs()],
external: ["the-answer"],
};
Copy the code
babel
The plug-in
Why is it neededbabel
The plugin?
We add the es6.js file to the SRC directory (⚠️ we used the arrow function in ES6 here) :
const a = 1;
const b = 2;
console.log(a, b);
export default() = > {return a + b;
};
Copy the code
Then modify the rollup.config.js configuration file:
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
export default {
input: ["./src/es6.js"].output: {
file: "./dist/esBundle.js".format: "umd".name: "experience",},plugins: [resolve(), commonjs()],
external: ["the-answer"]};Copy the code
You can see the dist/ esbundle.js file as follows:
(function (global, factory) {
typeof exports= = ='object' && typeof module! = ='undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeofglobalThis ! = ='undefined' ? globalThis : global || self, global.experience = factory()); } (this, (function () { 'use strict';
const a = 1;
const b = 2;
console.log(a, b);
var es6 = () = > {
return a + b;
};
return es6;
})));
Copy the code
As you can see, the arrow function is retained, and such code will not run in an environment that does not support ES6. We expect Babel to be used for code conversion during rollup.js packaging, so we need the Babel plug-in.
babel
Use of plug-ins
First, install:
npm i -D @rollup/plugin-babel
Copy the code
Also modify the rollup.config.js configuration file:
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import babel from "@rollup/plugin-babel";
export default {
input: ["./src/es6.js"].output: {
file: "./dist/esBundle.js".format: "umd".name: "experience",},plugins: [resolve(), commonjs(), babel()],
external: ["the-answer"]};Copy the code
Then pack and find an error:Remind us of the lack of@babel/core
Because the@babel/core
isbabel
The core of the. Let’s install:
npm i @babel/core
Copy the code
We did the packaging again and found no error this time, but we tried to open dist/ esbundle.js:
(function (global, factory) {
typeof exports= = ='object' && typeof module! = ='undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeofglobalThis ! = ='undefined' ? globalThis : global || self, global.experience = factory()); } (this, (function () { 'use strict';
const a = 1;
const b = 2;
console.log(a, b);
var es6 = (() = > {
return a + b;
});
return es6;
})));
Copy the code
You can see that the arrow function still exists, which is obviously not correct, indicating that our Babel plug-in is not working. Why is that?
The reason is because we are missing the. Babelrc file, add this file:
{
"presets": [["@babel/preset-env",
{
"modules": false.// "useBuiltIns": "usage"}}]]Copy the code
Babelrc is configured with preset env, so install this plugin first:
npm i @babel/preset-env
Copy the code
To do the packaging again, we open the dist/ esbundle.js file:
(function (global, factory) {
typeof exports= = ='object' && typeof module! = ='undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeofglobalThis ! = ='undefined' ? globalThis : global || self, global.experience = factory()); } (this, (function () { 'use strict';
var a = 1;
var b = 2;
console.log(a, b);
var es6 = (function () {
return a + b;
});
return es6;
})));
Copy the code
You can see that the arrow function is converted to function, indicating that the Babel plug-in is working properly.
json
The plug-in
Why use itjson
The plugin?
Create json.js file in SRC directory:
import json from ".. /package.json";
console.log(json.author);
Copy the code
It’s as simple as importing package.json and printing the Author field.
Modify the rollup.config.js configuration file:
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import babel from "@rollup/plugin-babel";
export default {
input: ["./src/json.js"].output: {
file: "./dist/jsonBundle.js".format: "umd".name: "experience",},plugins: [resolve(), commonjs(), babel()],
external: ["the-answer"]};Copy the code
The following error occurs when the package is executed:Remind us of the lack of@rollup/plugin-json
Plugins to supportjson
File.
json
Use of plug-ins
To install the plug-in:
npm i -D @rollup/plugin-json
Copy the code
Also modify the configuration file and add the plugins to the plugins array.
Then we package again, and seeing that the package is successful, we open the generated dist/jsonBundle directory:
(function (factory) {
typeof define === 'function'&& define.amd ? define(factory) : factory(); } ((function () { 'use strict';
var name = "rollup-experience";
var version = "1.0.0";
var description = "";
var main = "index.js";
var directories = {
example: "example"
};
var scripts = {
build: "rollup -c -w".test: "echo \"Error: no test specified\" && exit 1"
};
var author = "Cosen";
var license = "ISC";
var dependencies = {
"@babel/core": "^ 7.11.6"."@babel/preset-env": "^ 7.11.5"."the-answer": "^ 1.0.0"
};
var devDependencies = {
"@rollup/plugin-babel": "^ 5.2.0." "."@rollup/plugin-commonjs": "^ 15.0.0"."@rollup/plugin-json": "^ 4.1.0." "."@rollup/plugin-node-resolve": "^ 9.0.0"
};
var json = {
name: name,
version: version,
description: description,
main: main,
directories: directories,
scripts: scripts,
author: author,
license: license,
dependencies: dependencies,
devDependencies: devDependencies
};
console.log(json.author);
})));
Copy the code
Perfect!!!!!
tree-shaking
mechanism
Here we use the original SRC /index.js as an example:
import answer from "the-answer";
export default function () {
console.log("the answer is " + answer);
}
Copy the code
Modify the above files:
const a = 1;
const b = 2;
export default function () {
console.log(a + b);
}
Copy the code
Perform packaging. Open dist/bundle.js:
(function (global, factory) {
typeof exports= = ='object' && typeof module! = ='undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeofglobalThis ! = ='undefined' ? globalThis : global || self, global.experience = factory()); } (this, (function () { 'use strict';
var a = 1;
var b = 2;
function index () {
console.log(a + b);
}
return index;
})));
Copy the code
Change the SRC /index.js file again:
const a = 1;
const b = 2;
export default function () {
console.log(a);
}
Copy the code
Do the package again and open the package file:
(function (global, factory) {
typeof exports= = ='object' && typeof module! = ='undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeofglobalThis ! = ='undefined' ? globalThis : global || self, global.experience = factory()); } (this, (function () { 'use strict';
var a = 1;
function index () {
console.log(a);
}
return index;
})));
Copy the code
What was found?
We find that the definition of variable B is missing because it is not used in the source code. This is the well-known tree-shaking mechanism of the ES module, which dynamically cleans out unused code, making code leaner and making our libraries load faster.
conclusion
This article gives you an overview of what a rollup is and how to get started quickly. This is just the tip of the iceberg, but there’s a lot more rollup can do. Check out the rollup website for more
❤️ Love triple punch
1. If you think this article is good, share it, like it, and watch it again, so that more people can see it
2. Follow the public account front-end forest, regularly push you fresh dry goods good articles.
3. Wear a mask for personal protection at special stage.