In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to get started with Rollup quickly". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to get started with Rollup quickly.
What is rollup?
Before we systematically understand rollup, let's take a brief look at What is rollup.
With regard to the introduction to rollup, the official document has been written very clearly:
Rollup is a JavaScript module baler that compiles small chunks of code into large chunks of complex code, such as library or applications.
Unlike Webpack's preference for application packaging, rollup.js focuses more on Javascript class library packaging.
Many well-known frameworks or class libraries, such as Vue and React, are packaged through rollup.js.
Why rollup?
I'm sure all the front-end students have used webpack, so why do some scenarios still use rollup? Here I will briefly compare webpack and rollup:
Generally speaking, webpack and rollup can play their own advantages in different scenarios. Webpack has an "inherent advantage" for code segmentation and static resource import, and supports hot module replacement (HMR), while rollup does not.
So when developing applications, you can give priority to webpack, but rollup for the code of Tree-shaking and ES6 modules have algorithmic advantages of support, if your project only needs to package a simple bundle package, and is based on ES6 module development, you can consider using rollup.
In fact, webpack has supported Tree-shaking since 2.0, and it can also support es6 module packaging when using babel-loader. In fact, rollup has gradually lost its original advantage. But it has not been abandoned, on the contrary, it is favored by many library developers because of its simple API and usage, such as React, Vue and so on. They all use rollup as a building tool.
Get started quickly
Let's first take about ten minutes to understand the basic use of rollup and to complete a hello world.
Installation
First install rollup globally:
Npm i rollup-g
Directory preparation (hello world)
Next, we initialize a project directory as follows
├── dist # compilation result ├── example # HTML reference example │ └── index.html ├── package.json └── src # Source └── index.js
First, let's write the following code in src/index.js:
Console.log ("Coulson")
Then execute the following command on the command line:
Rollup src/index.js-f umd-o dist/bundle.js
By executing the command, we can generate the bundle.js file in the dist directory:
(function (factory) {typeof define = = 'function' & & define.amd? Define (factory): factory ();} ((function () {'use strict'; console.log ("Coulson");})
At this point, we introduce the above packaged bundle.js file into example/index.html and open the browser: as we expected, the console outputs Coulson.
At this point, we have packaged the simplest demo in rollup.
Many students may see that the parameters in the above command line are not very clear here, so let me explain them in turn:
-f. The-f parameter is an acronym for-- format, which indicates the format of the generated code, amd for the AMD standard, cjs for the CommonJS standard, and esm (or es) for the ES module standard. The value of-f can be any of amd, cjs, system, esm ('es' can also be), iife, or umd.
-o. -o specifies the output path. Here, we output the packaged file to bundle.js in the dist directory.
In fact, in addition to these two, there are many other commonly used commands (here I will list the remaining two more commonly used, complete rollup command-line arguments):
-c. Specifies the configuration file for the rollup.
-w. Listen for changes to the source file, and if so, repackage.
Use profile (rollup.config.js)
Using the command line approach, there is no problem if there are fewer options, but if you add more options, this command line approach is troublesome.
To do this, we can create a configuration file to include the options we need
Create a file called rollup.config.js in the project, adding the following code:
Export default {input: [". / src/index.js"], output: {file: ". / dist/bundle.js", format: "umd", name: "experience",},}
Then the command line executes:
Rollup-c
When we open the dist/bundle.js file, we will find that the result is the same as that packaged on the command line above.
Here, I give a brief description of the options for the configuration file:
Input indicates the path to the entry file (the old version is entry, which has been abandoned)
Output represents the contents of the output file, which allows you to pass in an object or an array, and when it is an array, output multiple files in turn, which contains the following:
Output.file: the path to the output file (the old version is dest, which is obsolete)
Output.format: format of the output file
Output.banner: what is added in the file header
Output.footer: what is added at the end of the file
At this point, I believe you have almost started rollup.
Advanced level
However, this is far from enough for real business scenarios.
Next, I'll introduce several common plug-ins in rollup, as well as external properties and tree-shaking mechanisms.
Resolve plug-in
Why use the resolve plug-in
In the above starter case, the objects we packaged are local js code and libraries, but in actual development, it is unlikely that all libraries are located locally, and we mostly download remote libraries through npm.
Unlike other bundles like webpack and browserify, rollup doesn't know how to break the rules to deal with these dependencies. So we need to add some configurations.
Resolve plug-in use
First add a dependent the-answer to our project, and then modify the src/index.js file:
Import answer from "the-answer"; export default function () {console.log ("the answer is" + answer);}
Execute npm run build.
For convenience here, I added the original rollup-c-w to package.json 's scripts: "build": "rollup-c-w"
You will get the following error:
The packaged bundle.js still works in Node.js, but the-answer is not included in the package. To solve this problem, merge the source code we wrote with dependent third-party libraries, and rollup.js provides us with the resolve plug-in.
First, install the resolve plug-in:
Npm I-D @ rollup/plugin-node-resolve
Modify the 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 ()],}
When you execute npm run build again, you can find that the error message is gone:
Open the dist/bundle.js file:
(function (global, factory) {typeof exports = = 'object' & & typeof module! = =' undefined'? Module.exports = factory (): typeof define = = 'function' & & define.amd? Define (factory): (global = typeof globalThis! = '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;})
The referenced module is already included in the package file bundle.js.
In some scenarios, although we use the resolve plug-in, we may still want some libraries to remain externally referenced, so we need to use the external attribute to tell rollup.js which external class libraries are.
External attribute
Modify the configuration file for rollup.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 ()], external: ["the-answer"],}
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 = typeof globalThis! = =' 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;})
At this point we see that the-answer has been introduced as an external library.
Commonjs plug-in
Why do you need the commonjs plug-in
The module in the rollup.js compiled source code refers to the module mode import/export, which only supports ES6+ by default. However, a large number of npm modules are based on CommonJS modules, which leads to a large number of npm modules can not be compiled and used directly.
As a result, plug-ins that support npm modules and CommonJS modules for rollup.js compilation come into being: @ rollup/plugin-commonjs.
Commonjs plug-in use
First, install the module:
Npm I-D @ rollup/plugin-commonjs
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"],}
Babel plug-in
Why do I need the babel plug-in?
Let's add the es6.js file in the src directory (⚠️ here we use the arrow function in es6):
Const a = 1; const b = 2; console.log (a, b); export default () = > {return a + b;}
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"],}
After performing packaging, you can see that the contents of the dist/esBundle.js file are as follows:
(function (global, factory) {typeof exports = = 'object' & & typeof module! = =' undefined'? Module.exports = factory (): typeof define = = 'function' & & define.amd? Define (factory): (global = typeof globalThis! = '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;})
You can see that the arrow function is preserved, and such code will not run in an environment that does not support ES6. We expect to be able to use babel for transcoding during rollup.js packaging, so we need the babel plug-in.
Use of the babel plug-in
First, install:
Npm I-D @ rollup/plugin-babel
Also modify the configuration file rollup.config.js:
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"],}
Then pack it and find that there will be an error:
It is suggested that @ babel/core is missing because @ babel/core is the core of babel. Let's do the installation:
Npm I @ babel/core
Execute the package again and find that there is no error this time, but we try 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 = typeof globalThis! = '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;})
You can see that the arrow function still exists, which is obviously incorrect, indicating that our babel plug-in is not working. Why is that?
The reason is that we lack the .babelrc file, so add it:
{"presets": [["@ babel/preset-env", {"modules": false, / / "useBuiltIns": "usage"}]}
Let's see. Babelrc is configured with preset env, so install this plug-in first:
Npm I @ babel/preset-env
To perform the packaging again this time, 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 = typeof globalThis! = '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;})
You can see that the arrow function is converted to function, indicating that the babel plug-in is working properly.
Json plug-in
Why use the json plug-in?
Create a json.js file in the src directory:
Import json from ".. / package.json"; console.log (json.author)
The content is simple: introduce package.json, and then print 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"],}
When performing packaging, the following error is found:
Prompts us that we lack the @ rollup/plugin-json plug-in to support json files.
Use of the json plug-in
To install the plug-in:
Npm I-D @ rollup/plugin-json
Also modify the configuration file to add the plug-in to the plugins array.
Then pack it again and find 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);}))
Perfect!
Tree-shaking mechanism
Here we take the original src/index.js as an example:
Import answer from "the-answer"; export default function () {console.log ("the answer is" + answer);}
Modify the above documents:
Const a = 1; const b = 2; export default function () {console.log (a + b);}
Perform packaging. Open the dist/bundle.js file:
(function (global, factory) {typeof exports = = 'object' & & typeof module! = =' undefined'? Module.exports = factory (): typeof define = = 'function' & & define.amd? Define (factory): (global = typeof globalThis! = '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;})
Modify the src/index.js file again:
Const a = 1; const b = 2; export default function () {console.log (a);}
Perform the packaging 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 = typeof globalThis! = 'undefined'? GlobalThis: global | | self, global.experience = factory ();} (this, (function () {'use strict'; var a = 1; function index () {console.log (a);} return index;})
What did you find?
We found that the definition of the variable b is gone because it is not used in the source code. This is the famous tree-shaking mechanism of the ES module, which dynamically clears the unused code, making the code more concise, thus enabling our class library to load faster.
At this point, I believe you have a deeper understanding of "how to get started with Rollup quickly". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.