Pre-knowledge – Rollup basics
What is a rollup
Rollup is a javascript module wrapper that compiles small blocks of code into complex chunks. When writing an application or library using the ES6 module, it can be packaged into a separate file for use by the browser and Node.js.
advantages
- Combine multiple files we have written into a single file
- Statically analyze code, eliminate unused code blocks, keep useful code blocks, reduce the size of packaged files (tree-shaking)
- Node modules are supported in the browser
- Based on ES2015 modules, it is more efficient than CommonJs modules used by WebPack
Warn: Tree-shaking is only supported in ES6 modules, not in CommonJs. And import should be used instead of require.
Application scenarios
Rollup is much smaller and simpler than WebPack, and is better suited for building libraries where your project needs to split code, contain resources such as images, fonts, etc. Webpack is better than rollup.
Based on using
export default {
input:'src/index.js'.output: {file:'dist/index1.iife.js'.format:'iife'}}Copy the code
- Input: rollup entry file for execution
- Output: indicates file output configuration
- Output. file: indicates the path name of the output file
- Output. format: rollup supports multiple output formats
- Iife: Outputs the format type for the browser
- CJS: Format type used for NodeJs
- Umd: Can be used for both browsers and NodeJs
- Amd: Type used for loading modules like RequireJs
How to process and package JS files
-
Install a rollup
Open the terminal and execute the command line NPM install –global rollup
-
Command line packaging
Create a new main.js file and add the following code:
const _keys = function(obj){
if(Object.prototype.toString.call(obj) ! = ='[object Object]') {throw new Error('type is error')}const hasOwnProperty = Object.prototype.hasOwnProperty;
let result = [];
for(let prop in obj){
if(hasOwnProperty.call(obj,prop)) result.push(prop)
}
return result;
}
export default _keys;
Copy the code
When the terminal runs the command line, you can see that the bundle.js file is generated, and the arguments after –format can be replaced with the above four types.
rollup main.js --file bundle.js --format iife
- Rollup.config. js is packaged as a configuration file
Using command line packaging each time can be complex and difficult to customize various configurations. Rollup provides a configuration file to simplify command-line operations and enable rollup’s complex operations.
This configuration file defaults to the rollup.config.js file, which is normally created in the root directory of the project. The above code is the basic content of the rollup.config.js file. In addition, it has other configuration items such as plugins, external, global, etc.
External: When the package tells Rollup not to package external dependencies specified by external. Global: Specifies a global variable of type Iife, umD. The Window object specifies it as a property plugins: group of pluginsCopy the code
Pre-knowledge — The Vue plug-in
Plugins are commonly used to add global functionality to a Vue, using the global method vue.use (plugins). It needs to be called before vUE is instantiated.
Vue.use() automatically prevents the same plug-in from being registered multiple times, even if it is called multiple times.
Vue. Use ()
The following figure is taken from use.js file of Vue source code global-API. It exports an initUse method with arguments passed to Vue. The internal use method receives the plugins parameter, which is the plug-in we wrote. It also defines an array that returns plugins when they are passed in. That is, the implementation automatically prevents multiple registrations of the same plug-in.
Const args = toArray(arguments,1) converts the passed argument to an array, and args. Unshift (this) adds the Vue object to the header of the array.
If the plugin passed in is an object and it contains an install method, the Plugin object’s Install method is called and the args argument is passed to it.
If plugin is itself a method, call it directly, passing in the args argument
Plug-in development
From the source code analysis above, we know that the plug-in passed in vue.use () must be either an object or a function, and when it is, the object must contain an install method. Typically, we develop plug-ins in the form of objects.
//myplugin.js
const install = function(Vue){
Vue.component('my-input', {template:' Custom component
})}export default {
install
}
Copy the code
//main.js
import Vue from 'vue'
import plugin from './plugins/myplugin.js'
Vue.use(plugin)
Copy the code
This is a simple plugin that can be added to app.vue by adding
Example: Package vUE components with rollup
- Create a new project and execute within the project
npm init -y
Initialize - Create file directories and files according to the following project structure
Fill the corresponding code in the corresponding file as follows:
// packages/button/index.js
import WnButton from './src/index.vue'
WnButton.install = function(Vue){
Vue.component(WnButton.name,WnButton)
}
export default WnButton;
Copy the code
// packages/button/src/index.vue
<template>
<button>
<slot></slot>
</button>
</template>
<script>
export default {
name:"WnButton"
}
</script>
Copy the code
// src/index.js
import Button from '.. /packages/button/index.js'
const components = [
Button
]
const install = function(Vue){
components.forEach(component= > {
Vue.component(component.name,component)
})
}
export default {
install
}
Copy the code
// rollup.config.js
export default {
input:'src/index.js'.output: {file:'lib/index.umd.js'.format:'umd'.name:'vue-plugins'}}Copy the code
Parse and compile vUE files
At this point, the simple code filling is complete, then change the package.json file, add “build”:”rollup -c” to the “script “, and finally run the command NPM run build at the terminal.
As you can see, instead of packing as we thought it would, it throws us an error telling us that we need to use the appropriate plug-in to handle non-javascript code.
We need to rely onrollup-plugin-vue
,vue-template-compiler
To parse the vue file (Note: the version must match, this example rollup-plugin-vue is 5.x version, before downloading version 6.0 problems did not study). Then, inrollup.config.js
Fill in the code
import vuePlugin from 'rollup-plugin-vue'
export default{
plugins:[vuePlugin()]
}
Copy the code
These are just a few lines, and you can process vue files
Babel compiles ES6 syntax
If you have ES6 syntax in your JS code and you need to convert it to ES5, rollup provides us with the Babel plugin, you just need to reference the dependency and execute it in plugins.
Required dependencies :@rollup/plugin-babel, @babel/core, @babel/preset-env
Create a.babelrc file in the root directory and populate it
{
"presets": ["@babel/preset-env"]}Copy the code
Fill in the code in rollup.config.js
import babel from '@rollup/plugin-babel'
export default {
plugins:[
babel({
babelHelpers:'bundled'.exclude:'node_modules/**'}})]Copy the code
Parse the CSS, LESS, and SASS
The components we write are definitely not just JS statements and DOM structures, CSS styles are also an important part of the component. We can write styles directly as style tags in.vue files without any problems. This is not friendly, however, and we want to maintain the styling of components in.css files.
Example: We create a new folder assets in the project root directory, create a style/index.css file, fill it with some style code, and then import ‘.. / style/reset. Less ‘use
Executing the package command will throw an error at us, at which point we need to introduce a plug-in that can handle CSS
Postcss, a rollup – plugin – postcss
Fill the rollup. Config. Js
import postcss from 'rollup-plugin-postcss'
export default {
plugins:[
postcss({
extensions: ['.css'.'.less'].extract:'index.css'}})]Copy the code
- Extensions: Handles extensions contained in this array, allowing you to specify extension files
- Extract: If you do not use this configuration, the styles are packaged into the final package file. Using this configuration, styles can be packaged separately into specified files
If using extract, we use the plug-in in main.js as follows
import plugins from './plugins/lib/index.umd.js'
import './plugins/lib/index.css'
Copy the code