What is Rollup (next generation ES module bundler)

Be careful not to read the Rollup.js Chinese website, because it is translated by someone else, not updated in real time, I have seen this before always install error

Before looking up the related rollup use on the network, some articles are very difficult to understand the concept, no specific steps; Some articles are not detailed enough and have no context. So I plan to organize an article to reduce detours for the latecomers. I guarantee that this article is really hand in hand teaching, very grounded, because I am building a project to use while writing the article, not a project in the code, so the code is clear, no redundancy.

Why not use Webpack

When it comes to packaging tools, everyone thinks of Webpack, because the VUE and React scaffolding we use are all based on Webpack, and they have various loaders to help us solve various problems, which is very effective for development projects. But it generates a lot of logical code that is not written by us, such as some of its own module loading functions:

If you are developing JS libraries, the rigor of WebPack and the size of the packaged files are not suitable. Where there is a need, there is a tool, so rollup was created for developing JS libraries.

Rollup generates code that simply transcodes our code to the target JS, but it also generates javascript that supports UMD/CommonJS/ES if needed. Vue/React/Angular uses it as a packaging tool. If you look at the code on their website, you can see the shadow of rollup.

Quick start

1. Create a new project

Create an empty folder, such as rollupConfigDemo

2. Install the rollup

Open the project with vscode and execute the installation command

cnpm install rollup --save-dev
Copy the code

After executing, we found that the project produced some files automatically and saw a rollup in the package.

Add gitignore, ignoring files that don’t need to be uploaded

3. Create a rollup. Config. Js

We could have packaged it directly with CLI commands without configuration files, but adding more options would have made this command-line approach cumbersome. To do this, we can create a configuration file that contains the required options. Configuration files are written in JavaScript, which is more flexible than CLI. (Please see the official website for the package of CLI commands)

4. Write the files to be packaged

1. Create a SRC folder and create main.js(application entry)

2. Create a “Modules” folder.

Modules distinguishes between modules and the main entry. Modules allows you to design the file directory structure according to your own JS library.

5. Write the package command in package.json

6. Run the NPM run build command to view the output

We can see that the output is very clear, with no extra code like webPack

7. Use the packaged file

When we open this page we see a popover that says Hello from Rollup

Commonly used configuration

The configuration items are described briefly

1.input

Entry file address

2.output

output:{
    file:'bundle.js'.// Output file
    format: CJS, // 5 output formats: AMD/ES6 / iife/umd/CJSA', // must be provided when format is iife and UMd, which will be hung as A global variable in the window(browser environment) : window.a =... Sourcemap :true // generate bundle.map.js for debugging purposes}Copy the code

3.plugins

Configuration used by various plug-ins

4.external

external:['lodash'] // Tell rollup not to package this lodash as an external dependency
Copy the code

5.global

global: {'jquery':'$' // Tell rollup that the global variable $is jquery
}
Copy the code

Attached is a rollup profile for the React-Redux open source project

import nodeResolve from 'rollup-plugin-node-resolve' // Help find packages in node_modules
import babel from 'rollup-plugin-babel' // Rollup Babel plugin, ES6 to ES5
import replace from 'rollup-plugin-replace' // Replace some variables in the file to be packaged. For example, process does not exist in the browser and needs to be replaced
import commonjs from 'rollup-plugin-commonjs' // Convert packages with non-ES6 syntax to ES6
import uglify from 'rollup-plugin-uglify' / / package

const env = process.env.NODE_ENV

const config = {
  input: 'src/index.js'.external: ['react'.'redux'].// Tell rollup not to pack react,redux; Think of it as an external dependency
  output: { 
    format: 'umd'.// Output in UMD format, common to various module specifications
    name: 'ReactRedux'.// Packaged global variables such as window.reactredux on the browser side
    globals: {
      react: 'React'.// This is used in conjunction with external, indicating that global.React is the external dependency React
      redux: 'Redux'}},plugins: [
    nodeResolve(),
    babel({
      exclude: '**/node_modules/**'
    }),
    replace({
      'process.env.NODE_ENV': JSON.stringify(env)
    }),
    commonjs()
  ]
}

if (env === 'production') {
  config.plugins.push(
    uglify({
      compress: {
        pure_getters: true.unsafe: true.unsafe_comps: true.warnings: false}}}))export default config
Copy the code

Further use

1. The use of Babel

To properly parse our module and make it compatible with older browsers, we should include Babel to compile the output. Many developers use Babel in their projects so that they can use future versions of JavaScript features that are not supported by browsers and Node.js.

1.1 installation rollup – plugin – Babel

cnpm install rollup-plugin-babel --save-dev
Copy the code

1.2 configuration rollup. Config. Js

1.3 Adding the Babel configuration file babelrc

Add.babelrc to the SRC folder

There is something unusual about this setup.

First, we set “modules”: false, otherwise Babel will convert our modules to CommonJS before Rollup has a chance to do so, causing some of Rollup’s processing to fail.

Second, we put the.babelrc file in SRC, not in the root directory. This allows us to have different.babelrc configurations for different tasks, such as testing, if we need them later – it’s usually better to have separate configurations for individual tasks.

1.4 Installing @babel/core and @babel/preset-env

@babel/core is the core of Babel, we see that Babelrc has preset env configured, so these two plug-ins are installed

cnpm install @babel/core @babel/preset-env --save-dev
Copy the code

After installation, we see the contents of the package

Finally, by running NPM Run build, we see that the contents of the packaged files have been Babel converted into ES6 syntax to ES5 syntax

2. Reference to the node module

At some point, your project may depend on installing packages from NPM into the node_modules folder.

Unlike other bundled software such as Webpack and Browserify, Rollup doesn’t know how to handle these dependencies’ out of the box ‘- we need to add some plug-in configuration.

By default, only ES6+ module import/export is supported for module references in the rollup.js compilation source code. However, a large number of NPM modules are based on CommonJS modules, which leads to a large number of NPM modules cannot be compiled directly. This is why plugins that support NPM modules and CommonJS modules are available to assist rollup.js compilation.

  • The rollup-plugin-node-resolve plug-in allows us to load third-party modules
  • The @rollup/ plugin-Commons plug-in converts them to the ES6 version

2.1 Install @rollup/ plugin-nodes-resolve and @rollup/plugin-commonjs

cnpm install @rollup/plugin-node-resolve @rollup/plugin-commonjs --save-dev
Copy the code

If you have installed Rollup-plugin-commonjs, it will prompt you after installation

This package has been deprecated and is no longer maintained. Use @rollup/plugin Commonjs.

If you have rollup-plugin-node-resolve installed, you may encounter this situation as well, and the solution is similar. @rollup/plugin-node-resolve and @rollup/plugin-commonjs

The package content after installation is

2.2 configuration rollup. Config. Js

2.3 Use a third-party library lodash

cnpm install lodash --save-dev
Copy the code

Open SRC /main.js and use lodash

After running the NPM run build we saw a lot more content in the package. This code is the Ladash code, which we packaged and integrated.

Open the web page to view the output

2.4 Additional Supplements

If you don’t want third-party libraries packaged in and can use them outside, you can configure External in rollup.config.js

After running the NPM run build, I found that less content was packaged

Then the page usage is modified slightly, the script is introduced into lodash, the iife package is used (because we are using page references here), and the view page is output normally.

3. Use the typescript

When developing large projects, we typically use typescript to enhance the maintainability of our code. So using typescript in rollup is also essential.

3.1 installation @ rollup/plugin – typescript

I used to use rollup-plugin-typescript. As I write this article today, I find that the plugin is no longer maintained and the module is ported to @rollup/plugin-typescript

cnpm install @rollup/plugin-typescript --save-dev
Copy the code

After installation, we found an error telling us to install tslib and typescript

3.2 Installing Tslib and typescript

cnpm install tslib typescript --save-dev
Copy the code

After the installation, let’s take a look at the package contents

3.3 configuration rollup. Config. Js

Introducing plug-ins

3.4 configuration tsconfig. Json

If we run NPM run build without the configuration, we will be prompted to create a new tsConfig configuration

3.5 Writing TS Files

After running NPM Run build, the view page parses and runs properly

4. Compress the code

To keep the code smaller, we all use code compression plug-ins

4.1 installation rollup – plugin – terser

What is Terser, a JavaScript parser, Mangler, and compressor toolkit for ES6 +

We’re familiar with Uglify because we used it in WebPack, and rollup also has a rollup-plugin-Uglify plugin

Note that uglify-js can only translate ES5 syntax. If you want to translate es6+ syntax, use terser instead

So we use rollup-plugin-terser

cnpm install rollup-plugin-terser --save-dev
Copy the code

4.2 configuration rollup. Config. Js

With terser introduced, we run NPM run buld to see the output

5. Compile the CSS

We use WebPack to develop js libraries. Rollup is better than Webpack. If you are writing a lot of CSS, then you are probably developing a project and you prefer WebPack. Webpack also has the development library configuration.

If your JS library still needs to write CSS, Rollup also has plug-ins to compile CSS

5.1 installation rollup – plugin – postcss

cnpm install rollup-plugin-postcss --save-dev
Copy the code

5.2 configuration rollup. Config. Js

Introduce the PostCSS plug-in and use it. First comment out the compression plug-in so we can see what the packaged CSS looks like.

5.3 Writing and using CSS

1. Write the style. CSS file to the SRC directory

2.main.js to write the related CSS usage code

3. Run the NPM run build command to view the content of the package. We see CSS introduced dynamically through this piece of code

4. Open the page to view the HTML code

Pre-compilations such as less are also available. Ask me questions and I will update if necessary.

6. Distinguish between development and production environments

In the development environment we need sourcemap on and configure hot updates and local services, in the production environment we need Sourcemap off, no hot updates and local services, code compression and so on, so we need to distinguish.

6.1 Split rollup.config.js into two rollup.config.dev.js and rollup.config.build.js

6.2 Changing the package name in package.json

7. Start the local server

In real development, where we definitely want to run code and look at pages, it’s important to have a local server so you can debug your code.

7.1 installation rollup – plugin – serve

cnpm install rollup-plugin-serve --save-dev
Copy the code

7.2 configuration rollup. Config. Js

Remember to configure sourcemap: true to make debugging code easier.

Remember to create an index. HTML file in the root directory to reference the JS library

Configure the naming in package.json (this has been modified to distinguish between development and production environments, see below for this configuration)

7.3 Or use rollup-plugin-dev

This plug-in provides the following features compared to Serve

cnpm install rollup-plugin0dev --save-dev
Copy the code

7.4 configuration rollup. Config. Dev. Js

8. Enable hot update

Now the local server is available, but every time you change your code, you have to restart, which is inconvenient, so you need hot updates.

8.1 installation rollup – plugin – livereload

cnpm install rollup-plugin-livereload --save-dev
Copy the code

8.2 configuration rollup. Config. Dev. Js

9. Multiple I/O files

Rollup supports processing multiple input and output files at once, and Watch Mode supports detecting multiple entry files, which are wrapped in an array. For example,

export default [
  // The first entry file
  {
    input: "main-a.js".output: {
      file: "dist/bundle-a.js".format: "cjs"}},// The second entry file
  {
    input: "main-b.js".output: [
      // Multiple output files
      {
        file: "dist/bundle-b1.js".format: "cjs"
      },
      {
        file: "dist/bundle-b2.js".format: "esm"}}]];Copy the code

This pattern is not common. A more common pattern is the previous one entry file, multiple output files, where the output files differ by using different module definitions, such as the ES6 module and CommonJS module.

10. Replace relative paths with aliases

Rollup plug-in to define aliases when packaging packages.

10.1 installation @ rollup/plugin – alias

cnpm install @rollup/plugin-alias --save-dev
Copy the code

10.2 configuration rollup. Config. Dev. Js

If it is used, both the dev and build environments need to be modified

10.3 Importing modified Files

11. More plug-ins

11.1 @ rollup/plugin – image

JPG, PNG, GIF, SVG and WebP files can be imported.

The images are base64 encoded, which means they will be 33% larger than their on-disk size. For more details, see github.com/rollup/plug…

11.2 @ rollup/plugin – json

Json files can be converted to ES6 modules. For more details, see github.com/rollup/plug…

11.3 a rollup – plugin – copy

Copy files and folders with glob support. For more details, see github.com/vladshcherb…

11.4 a rollup – plugin – visualizer

Visualize and analyze your Rollup bundle to see which modules are taking up space. For more details, see github.com/btd/rollup-…

11.5 a rollup – plugin – web – worker – loader

Work with Web workers. For more details, see github.com/darionco/ro…

Package axiOS exception issues

The issue of wrapping axios exceptions in rollup is documented in this article juejin.cn/post/685457…

All of the above rollup-plugins are available on Github. For details on how to use the plugin, see the plugin documentation

Continuously updated

Github.com/rollup/plug…

Github.com/rollup/awes…

The two rollup plug-ins are associated with the plugin address, and the desired functionality is found here