Preface, why learn RollUp? The vUE framework source code is packaged using Rollup. So you need to learn. And rollup is more suitable for framework development than Webpack. The packaged code is more readable.
Introduce a Rollup
- EsModule packaging machine
- The scattered small modules in the project are packaged into whole pieces of code, so that the small modules can better run in the browser environment and nodeJS environment
- What it does: Very similar to WebPack
- Comparison: Rollup is smaller than WebPack, which can fulfill the engineering requirements of a project, while Rollup is just an ESM (ESmodule) packer without any other functionality. For example, HMR (hot replace) is available in Webpack and not in Rollup
- Rollup’s purpose: To provide an efficient packer that takes full advantage of ESM features. Using various features of ESmodule to build a relatively flat structure, the performance of a relatively superior class library.
The Rollup speaking
I. New projects
Created a super simple project for learning, the project code is to esModule specification for project modularization, project directory is as follows:
rollup
├ ─ SRC
├ ─ ─ the js
├ ─ ─ sum. Js
├ ─ ─ index. Js
├ ─ package. Json
└ ─ yarn. The lock
//index.js
import { log } from './log.js';
import { sum } from './sum.js';
console.log('hello');
console.log(sum(2, 3));
Copy the code
//log.js
export function log(argu) {
console.log(argu);
}
Copy the code
//sum.js
export function sum(num1, num2) {
return num1 + num2;
}
Copy the code
Install Rollup
Install Rollup as a development dependency.
yarn add rollup –dev
After installation, in the project Node-modules, there is the rollup.cmd command. Rollup can be used on the command line for packaging.
Using the yarn command, you can directly run the commands in the bin folder of node-modules instead of the command directory.
Three, use,
1. Try rollup
yarn rollup
A help message is automatically printed when no parameters are passed
use settings in config file
rollup -c
Copy the code
Help tip: A package entry file should be specified with a parameter
2. Configure the package entry file
Create a new index.js file
yarn rollup ./src/index
After executing the above command, the console outputs the packaged content. The output is mixed with the methods of the introduced file, etc. Put the introduced methods in the header and the file’s own code at the bottom.
Next we give rollup an output format for the packaged file to control what format to output in.
3. Configure the output format of the packaged file
Use –format to configure the packaging format after the packaging command.
yarn rollup ./src/index.js –format iife
Iife is a self-executing function format available in the browser environment
$H:\xp\rollup\node_modules.bin\rollup./ SRC /index.js --format iife./ SRC /index.js → stdout... (function () { 'use strict'; function log(msg) { console.log(msg); } var message = { hi: 'hello' }; function sum(num1, num2) { return num1 + num2; } //index.js const hi = message.hi; log(hi); log(sum(2 + 3)); }) ();Copy the code
4. Configure the package output file path
yarn rollup ./src/index.js –format iife –file dist/bundle.js
You can use –file to configure the output file to which the packaging results are printed.
5. View the packaged output file
(function () { 'use strict'; function log(msg) { console.log(msg); } var message = { hi: 'hello' }; function sum(num1, num2) { return num1 + num2; } //index.js const hi = message.hi; log(hi); log(sum(2 + 3)); }) ();Copy the code
Look at the package output file, the package output is very simple, the same as our handwritten code, compared to the webpack a lot of boot code, and a bunch of module functions, the Rollup package output is almost no extra code, it is the process of packaging us, Each module is pieced together in the order of module dependencies, and in the output, it only preserves the parts that are used. There is no output for the unreferenced parts because Rollup automatically turns on Treeshaking by default, which was first introduced in Rollup.
Rollup configuration file
Rollup also supports configuration files to configure parameters during the packaging process
1. Create a configuration file in the project root directory
In the root directory of the project, create a rollup.config.js configuration file. This configuration file also runs in the Node environment, but rollup handles this configuration file itself, so we can use ESmodule directly here. The file needs to export a configuration object from which we can pass
- The input property specifies the path to the entry file we packed
- Output specifies the configuration of the output. The output format requires an object
-
- In the output object, use
file
Property to specify the output filename - In the output object, use
format
Property to specify our output format.
- In the output object, use
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife'
}
};
Copy the code
Run the rollup command. The –config command indicates that the configuration file in the project is used. The configuration file is not read by default
yarn rollup –config
Different configuration files can be used in projects for development and production environments, for example:
yarn rollup –config rollup.dev.config.js
yarn rollup –config rollup.pro.config.js
Rollup uses plug-ins
Rollup itself is simply a merging package of ESModel modules, so if our project has more advanced requirements, for example
- Want to load other types of resource files
- You want to import the CommonJS module in your code
- Want to Rollup to help us compile EMCAScript’s new feature
Rollup supports extensions to implement these additional requirements using plug-ins, which are unique to Rollup, unlike webPack, which divides the loader, plugin, and Minimizer extensions.
rollup-plugin-jsonThe plug-in
Install and import the rollup-plugin-json plug-in to introduce and use JSON files in your project. In the following example, after the plug-in is installed, the package is imported in the rollup configuration file, and the values in the package.json file can be imported in the index.js file.
How to use plug-ins in Rollup
1. Install rollup-plugin-json as development dependency
yarn add rollup-plugin-json –dev
2, use,import
To import the plugin module.
Add the result of the call to our plugins array. Note that we are putting the result of the call into the array, not directly into the function.
import json from 'rollup-plugin-json'
export default{
input:'src/index.js',
output:{
file:'dist/bundle.js',
format:''
},
plugins:[
json()
]
}
Copy the code
3. Try using the plug-in introduced so far in the project file. Open the project SRC /index.js file
//src/index.js import {name,version} from '.. /package.json' console.log(name) console.log(version)Copy the code
Execute the package command to run the package:
yarn rollup –config
After packaging, we find the bundle.js output, and you can see that the name and version in package.json are packaged normally, and the properties that are not used in json are also shaken off by the Tree.
(function () { 'use strict'; function log(msg) { console.log(msg); } var message = { hi: 'hello' }; function sum(num1, num2) { return num1 + num2; } var name = "rollup"; //index.js const hi = message.hi; console.log(name); log(hi); log(sum(2 + 3)); }) ();Copy the code
Rollup Loads the NPM module
By default, Rollup can only load local file modules according to the file path. For third-party modules in nodd_module, Rollup cannot import modules by module name as webpack does. Rollup provides a rollup-plugin-node-resolve plugin that allows you to import a module using the name of the module in your code.
1. Install rollup-plugin-node-resolve
yarn add rollup-plugin-node-resolve –dev
2. Modify the configuration file
Open the configuration file, import the plug-in, and then configure the results of the plug-in function call into the plugin subarray
// rollup.config.js
import json from 'rollup-plugin-json';
import npm from 'rollup-plugin-node-resolve';
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife'
},
plugins: [json(), npm()]
};
Copy the code
3. Install the third-party module
Here’s an example of installing LoDash
yarn add lodash
4. Import the ESmodule version of LoDash
//index.js import { log } from './log.js'; import message from './message'; import { sum } from './sum.js'; import { name, version } from '.. /package.json'; // Use the newly installed lodash module import _ from 'lodash-es'; const hi = message.hi; let arr1 = _.first([2, 3, 4]); console.log(name); log(hi); log(sum(2 + 3));Copy the code
After the import, we can use some of the utility methods provided by this module
4. Open the cli terminal and run rollup to package
yarn rollup –config
The code in LoDash can then be packaged into boundle.js. The reason for introducing the ESmodule version of LoDash is because rollup only supports ESmodule modules by default, and requires extra processing if you want to use the normal version.
//dist/bundle.js (function (_) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var ___default = /*#__PURE__*/_interopDefaultLegacy(_); function log(msg) { console.log(msg); } var message = { hi: 'hello' }; function sum(num1, num2) { return num1 + num2; } var name = "rollup"; //index.js const hi = message.hi; ___default["default"].first([2, 3, 4]); console.log(name); log(hi); log(sum(2 + 3)); }) (_);Copy the code
Rollup loads the CommonJS module
Rollup is designed to handle ESmodule packaging only, so if we import commonJSl in our code, it is not supported by default. However, there are still a lot of NPM modules that use commonJS to export members, so in order to be compatible with these modules, Rollup-plugin-commonjs plugin is available now.
Method of use
A, install,rollup-plugin-commonjs
The plug-in
yarn add rollup-plugin-commonjs –dev
2. Modify the configuration file
Open the rollup package configuration file, import the rollup-plugin-commonJS plug-in, and add the execution result of the plug-in function to the pligUNS array.
// rollup.config.js
import json from 'rollup-plugin-json';
import npm from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'iife'
},
plugins: [json(), npm(), commonjs()]
};
Copy the code
Plugin CommonJs module file and use
Create a csS-module. js file in the directory and add a Commonjs module file to the project. \
//cjs-module.js
module.exports={
foo:'bar'
}
Copy the code
Import this module in index.js,
//index.js import { log } from './log.js'; import message from './message'; import { sum } from './sum.js'; import { name, version } from '.. /package.json'; // Use the newly installed lodash module import _ from 'lodash-es'; // Import CJS from './cjs-module'; // import CJS from '. const hi = message.hi; let arr1 = _.first([2, 3, 4]); log(name); log(cjs); log(hi); log(sum(2 + 3));Copy the code
4. Perform rollup packaging
yarn rollup –config
(function (_) { 'use strict'; function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var ___default = /*#__PURE__*/_interopDefaultLegacy(_); function log(msg) { console.log(msg); } var message = { hi: 'hello' }; function sum(num1, num2) { return num1 + num2; } var name = "rollup"; //cjs-module.js var cjsModule = { foo: 'bar' }; cjsModule.foo; //index.js const hi = message.hi; ___default["default"].first([2, 3, 4]); log(name); log(cjsModule); log(hi); log(sum(2 + 3)); }) (_);Copy the code
Rollup Code Splitting
In the latest Rollup release, code splitting is already supported, so modules can also be loaded on demand using ESmodule compliant dynamic imports, and code splitting (i.e., subcontracting) is handled automatically within Rollup.
One, return to the package entry file
//index.js // import the dynamic import method returns a promise. The then method fetches the object imported by the module. Here deconstruction to extract the import log method ('. / log). Then (({log}) = > {log (" hello "); });Copy the code
Then we use dynamic import to import the logger.js module. The import() method returns a Promise object, and in its.then() method we get an object from which the module imported the members. So you can extract the log method by destructing it, you can call the log() method,
Try running rollup for packaging
yarn rollop –config
SRC/index2. Js - dist/bundle. Js... [!] Error: Invalid value "iife" for option "output.format" - UMD and IIFE output formats are not supported for code-splitting builds. https://rollupjs.org/guide/en/#outputformat Error: Invalid value "iife" for option "output.format" - UMD and IIFE output formats are not supported for code-splitting builds. at error (H:\xp\rollup\node_modules\rollup\dist\shared\rollup.js:158:30) at validateOptionsForMultiChunkOutput (H:\xp\rollup\node_modules\rollup\dist\shared\rollup.js:16109:16) at Bundle.generate (H:\xp\rollup\node_modules\rollup\dist\shared\rollup.js:15948:17) at async handleGenerateWrite (H:\xp\rollup\node_modules\rollup\dist\shared\rollup.js:23480:23) at async Promise.all (index 0) at async build (H:\xp\rollup\node_modules\rollup\dist\bin\rollup:1576:5) at async runRollup (H:\xp\rollup\node_modules\rollup\dist\bin\rollup:1730:21) error Command failed with exit code 1.Copy the code
The reason is simple, because self-executing functions put all modules into the same function. It doesn’t have bootstrap Code like Webpack does. So it has no way to achieve code split, so if you want to use code split, you have to use AMD or Commonjs and other standards, so in the browser, we can only use AMD standard, so we need to use AMD format to output packaging results
Re-execute the package command to change the output format of the package file and override the format setting in the configuration file with the –format parameter to set it to AMD. Here, use –format AMD in the command to override the IIFE packaging format in the configuration file.
yarn rollop –config –format amd
The mode of Code Splitting, which requires the output of multiple files, should no longer be used, because file is the name of the file that we should output for a single file. If we need to output more than one file, we can use the dir argument
$H:\xp\rollup\node_modules.bin\rollup --config --format AMD SRC /index2.js → dist/bundle.js... [!] Error: Invalid value for option "output.file" - when building multiple chunks, the "output.dir" option must be used, not "output.file". To inline dynamic imports, set the "inlineDynamicImports" option. https://rollupjs.org/guide/en/#outputdir Error: Invalid value for option "output.file" - when building multiple chunks, the "output.dir" option must be used, not "output.file". To inline dynamic imports, set the "inlineDynamicImports" option. at error (H:\xp\rollup\node_modules\rollup\dist\shared\rollup.js:158:30) at validateOptionsForMultiChunkOutput (H:\xp\rollup\node_modules\rollup\dist\shared\rollup.js:16111:16) at Bundle.generate (H:\xp\rollup\node_modules\rollup\dist\shared\rollup.js:15948:17) at async handleGenerateWrite (H:\xp\rollup\node_modules\rollup\dist\shared\rollup.js:23480:23) at async Promise.all (index 0) at async build (H:\xp\rollup\node_modules\rollup\dist\bin\rollup:1576:5) at async runRollup (H:\xp\rollup\node_modules\rollup\dist\bin\rollup:1730:21) error Command failed with exit code 1.Copy the code
Modify the rollup package configuration file
export default{
input:'src/index.js',
output:{
//file:'dist/bundle.js',
//format:'IIFE'
dir:'dist',
format:'amd'
}
}
Copy the code
Execute the packing command, delete all files in the dist folder before executing the packing command, and output files after observing the subcontracting and packing
yarn rollup –config
The dist folder is split into two files.
//index.js define(['require'], (function (require) { 'use strict'; // import dynamic import methods return a promise. The then method fetches the object imported by the module. New Promise(resolve (reject) {require(['./log-ace3f028'], resolve, reject); }).then(({ log }) => { log('hello'); }); }));Copy the code
//log-ace3f028.js
define(['exports'], (function (exports) { 'use strict';
function log(msg) {
console.log(msg);
}
function error(msg) {
console.error(msg);
}
exports.error = error;
exports.log = log;
}));
Copy the code
Rollup multi-entry packing
Support multi-entry packaging.
For different entries in the file, the common parts are automatically extracted into a single file as bundles.
Configure multiple entry, set the input format to array, put multiple packaged entry files.
export default{
input:['src/index.js','src/']
output:{
//file:'dist/bundle.js',
//format:'IIFE'
dir:'dist',
format:'amd'
}
}
Copy the code
The IIFE output format cannot be used. You need to change the output format to AMD
You do the packaging, and when you do the packaging, you generate different entry files, and common extract common modules
Cannot be used directly on the page, need to use amd library load.
Introduce AMD modules using requireJs
<script src='' data-main=''></script>
Copy the code
Rollup and Webpack
- The output is more flat and efficient
- Automatically remove unreferenced code, Tree Shaking
- The package results are still fully readable
Disadvantages:
- Loading non-ESM third-party modules is complicated \
- Modules end up packaged into a function that does not implement HMR\
- In the browser environment, the code splitting function relies on the AMD library
If we are developing an application, rollup is lacking.
If we are developing a framework or library, most well-known frameworks/libraries use Rollup.