Before I start this chapter, I decided to start an article on rollup. After all, work requires foreplay.

Make a choice,rollup vs webpack

Webpack was founded in 2012 by Tobias Koppers to solve a problem that existing tools cannot: building complex single-page applications (spAs). In particular, two functions had a great influence on the later period:

  1. Code-splitting, with Code splitting, is a way to split your application into manageable chunks that can be loaded on demand. This means that your users will get an interactive site much faster than waiting for the entire application to download and parse.

  2. Static assets, which allows you to import Static assets such as images and CSS into your application and treat them as just another node in the dependency diagram.

Rollup was really created for another reason, to take advantage of the clever design of ES2015 modules to build a unified distributable version of the JavaScript library as efficiently as possible.

Let’s take a feature-by-feature look at the differences

The following is fromwebpackWebsite:webpack.js.org/comparison

function webpack rollup
According to the need to load Yes No
AMD define Yes rollup-plugin-amd
AMD require Yes No(Personal use discovery is supported)
AMD requireAccording to the need to load Yes No
CommonJS exports Yes commonjs-plugin
CommonJS require Yes commonjs-plugin
CommonJS require.resolve Yes No
Concat in require require("./fi" + "le") Yes No
Debugging support SourceUrl, SourceMaps SourceUrl, SourceMaps
Dependencies 19MB / 127 packages ? MB / 3 packages
ES2015 import/export Yes Yes
Plugins Yes Yes

Probably put out so much, other you can go to the link address to see.

From this comparison, we can see that webpack is a crushing defeat, and even rollup is a shame. What’s the point of living in this world when you can’t do anything?

Being is reasonable — Hegel

Let’s take an interesting comparison:

function webpack rollup
Dependencies 19MB / 127 packages ? MB / 3 packages

19 MB? What does it mean? This means that a user at 1m/s will need 19s to download this JS file. Scary, isn’t it? At this point, you suddenly think, I can compress, yes, we can compress with Uglify or Terser, but, still, we can’t avoid, 19M even with compression, we can only compress around 6M, if we use the split chunk form, we can reduce the main package to around 2M, But that’s still a scary number. Blank projects are all this size, and we’ll introduce other packages.

Rollup, on the other hand, noticed this, so the blank items we packed with rollup were only a few kilobytes.

Use webpack for apps, and Rollup for libraries

Yes, WebPack is powerful, but it also has application scope, the application is its base, if it is a library, it can use rollup.

2. Use and pack onejs-sdk

First, we set a requirement that we collect performance data from our users.

Open the nuggets recommended page, https://juejin.im/timeline/recommended, we can enter the following code in chrome console, get the data as shown in figure 1:

console.log(performance.getEntries());
Copy the code

To prepare data

What we need now is to collect the data before this data and report it to the back end for data analysis.

// lib/PerformanceEntries.js
export default class {
  constructor() {
    this.entries = this._handleEntries();
  }

  _handleEntries() {
    const entries = window.performance.getEntries();
    const fptIndex = entries.findIndex(entry= > entry.entryType === 'paint');
    return entries.slice(0, fptIndex);
  }

  getEntries() {
    return this.entries; }}Copy the code

We need to report this data

import PerformanceEntries from './lib/PerformanceEntries';

(async () = > {
  const performanceEntries = new PerformanceEntries();
  const entries = performanceEntries.getEntries();
  try {
    const res = await fetch('https://server.save.data/api/v1/entries', {
      method: 'POST'.body: JSON.stringify(entries),
    });
    // some code...
  } catch {}
})();
Copy the code

Write arollup.config.js

import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import resolve from 'rollup-plugin-node-resolve';
import { terser } from 'rollup-plugin-terser';

import { version } from './package.json';

export default {
  input: 'index.js'.// Import file
  output: {
    file: 'dist/performance.{version}.js'.// The file name and location of the package
    format: 'umd'.Support umD, CMD, ESM...
    name: 'ihap'.// The name of the exported file
    exports: 'named',},plugins: {
    babel({
      exclude: ['node_modules']./ / ignore node_modules
      runtimeHelpers: true.// Enable volume optimization
    }),
    commonjs(),
    resolve({
      mainField: ['jsnext'.'main'].browser: true,
    }),
    terser(),
  },
}
Copy the code

babelrcStill indispensable

{
  "presets": [["@babel/preset-env",
      {
        "targets": {
          "esmodules": true}}]],"plugins": [
    "@babel/plugin-external-helpers"."@babel/plugin-transform-runtime"["@babel/plugin-proposal-class-properties", { "loose": true}}]]Copy the code

Execute and see the results

Ok, that’s fine. Let’s do rollup -c, okay

Take a look at the size of the file we packed

It’s only 772B, which is pretty impressive.

So the question is, can it be used? Ok, so let’s just write a simple Node and do it.

Look, our results went out.

Summary of this episode & next episode preview

We’ve learned how to package a very small file with rollup, and in the next slide, we’ll look at how to perform performance analysis. Ok, see you next time, I am the fat little iHAP technology black hole, like my words, remember to focus on the praise collection, love me can support me on wechat to give me praise ah!