Due to the previous mainly do Web page development, so use webpack to package. Now we’ve moved from Web pages to SDK development, and packaging tools have moved from WebPack to Rollup. Document the rollup features and usage here.

rollup

Brief introduction:

Rollup is a JavaScript module wrapper that compiles small pieces of code into large, complex pieces of code, such as libraries or applications

  • Pros: Small and focused

Application Scenarios:

Open source projects using Rollup:
  • vue
  • vuex
  • vue-router

Rollup vs. Webpack

The name of the Introduction to the The open source project
rollup Is a JavaScript module wrapper that compiles small pieces of code into large, complex pieces of code, such as libraries or applications vue, vuex, vue-router
webpack Module Bundler is a static module bundler for modern JavaScript applications. When WebPack works with an application, it recursively builds a Dependency graph containing every module the application needs, and then packages all of those modules into one or more bundles. element-ui, mint-ui, vue-cli
It can be roughly analyzed from the above application scenarios that Rollup bias is applied to JS library, Webpack bias is applied to front-end engineering, UI library; If your application scenario is just JS code and you want to do ES conversion and module parsing, use Rollup. If your scenario involves CSS, HTML, and complex code splitting and merging, webPack is recommended.

use

Install Rollup and create the configuration file using the following command
 yarn add --save-dev rollup
Copy the code
Create a new file rollup.config.js in the root directory of your project and add the following code to the file:
export default {
  input: './src/index.js'.output: {
    file: './dist/sdk.min.js'.format: 'umd'}}Copy the code

Next, understand the meanings of each configuration:

input:
Rollup first executes the entry fileCopy the code
The output:
Rollup output file.Copy the code
output.format:
Rollup supports multiple output formats (amd, CJS, ES, IIFE and UMD)Copy the code

We add the following script under package.json code:

"scripts": {
  "build": "rollup -c"
}
Copy the code

To complete the package, enter yarn run build on the command line

SRC /utils/utils.js:

export function a(name) {
  const str = I was `${name}! `;
  return str;
}
export function b(name) {
  const str = He is a `${name}! `;
  return str;
}
Copy the code

src/utils/addArray.js

/ * * *@param  {Array} arr
 * @return {Number}* /
const addArray = arr= > {
  const result = arr.reduce((a, b) = > a + b, 0);
  return result;
};
export default addArray;
Copy the code

src/index.js

import { a } from './utils/utils';
import addArray from './utils/addArray';

const res1 = a('Lao wang');
const res2 = addArray([1.2.3.4]);

console.log(res1);
console.log(res2);
Copy the code

Dist/sdK.min.js will be generated in the root directory of the project, with the following code:

(function (factory) {
    typeof define === 'function'&& define.amd ? define(factory) : factory(); } ((function () { 'use strict';

    function a(name) {
        const str = I was `${name}! `;
        return str;
    }

    / * * *@param  {Array} arr
     * @return {Number}* /
    const addArray = arr= > {
        const result = arr.reduce((a, b) = > a + b, 0);
        return result;
    };

    const res1 = a('Lao wang');
    const res2 = addArray([1.2.3.4]);

    console.log(res1);
    console.log(res2);

})));
Copy the code

SRC /utils/a.js: SRC /utils/a.js: SRC /utils/a.js: SRC /utils/a.js

Note: after the above code is packaged, only modern browsers will work, we need to add some plug-ins to make it work with older browsers that don’t support ES2015.

Use the plug-in Babel to convert ES6 code to support older browsers

As packaged above, we can run it in modern browsers, but if we use older browsers, we will get an error. At this point we need to use Babel for the transformation

First you need to install some dependencies:

yarn add @babel/core @babel/preset-env @babel/plugin-external-helpers rollup-plugin-babel --save-dev
Copy the code
Note: Babel Preset is a set of Babel plug-ins that tells Babel what we need to be translated.
Create the.babelrc file

Create a new.babelrc file in the root directory of your project and add the following JSON code:

{
    "presets": [["@babel/preset-env",
            {
                "modules": false}]],"plugins": ["@babel/plugin-external-helpers"]}Copy the code

Then add the Babel plugin to rollup.config.js:

// Rollup plugins
import babel from 'rollup-plugin-babel';

export default {
  input: './src/index.js'.output: {
    file: './dist/sdk.min.js'.format: 'umd'
  },
  plugins: [
    babel({
      exclude: 'node_modules/**'  // Exclude all files under node_module}})]Copy the code

To avoid translating third-party scripts, we need to set a exclude configuration option to ignore all files in the node_modules directory. When the installation is complete, we rerun the command; Then the packaged code looks like this:

(function (factory) {
    typeof define === 'function'&& define.amd ? define(factory) : factory(); } ((function () { 'use strict';

    function a(name) {
      var str = "\u6211\u662F".concat(name, "!");
      return str;
    }

    / * * *@param  {Array} arr
     * @return {Number}* /
    var addArray = function addArray(arr) {
      var result = arr.reduce(function (a, b) {
        return a + b;
      }, 0);
      return result;
    };

    var res1 = a('Lao wang');
    var res2 = addArray([1.2.3.4]);
    console.log(res1);
    console.log(res2);

})));
Copy the code

If we compare the code, we can see that addArray’s arrow functions parse into real functions. After the translation runs, the code is pretty much the same, except that it already supports older browsers.

Note: Babel also provides Babel-Polyfill, which also works in browsers prior to IE8.

Add Uglify plug-in compression code

The installation command is as follows:
yarn add rollup-plugin-uglify
Copy the code

In order to make the code more readable during development, we will only compress the code in production: rollup.config.js config code is as follows:

// Rollup plugins
import babel from 'rollup-plugin-babel';
import uglify from 'rollup-plugin-uglify';

export default {
  input: './src/index.js'.output: {
    file: './dist/sdk.min.js'.format: 'umd'
  },
  plugins: [
    babel({
      exclude: 'node_modules/**'  // Exclude all files under node_module
    })
    // the js compression plugin needs to be introduced at the end
    uglify(),
  ]
}
Copy the code