Lightweight Library packaging tool

Introduction to the

Address of this document

  • Blog address
  • The demo making address

This article refers to the reference document address

  • Rollup official Chinese document
  • Rollup builds JS packages
  • Rollup package JS notes
  • Personal understanding of Babel 7 use

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

Rollup uses new standardized formats for code modules that are included in the ES6 version of JavaScript, rather than previous ad-hoc solutions such as CommonJS and AMD. ES6 modules allow you to use the most useful stand-alone functions in your favorite library freely and seamlessly, without having to carry around other unused code in your projects. ES6 modules will eventually be implemented natively in the browser, but the current Rollup gives you an early taste.

Why is rollup

Rollup is built with an eye to the future, using the modular mechanism of the native ES standard. The ES specification of the future will be implemented by browsers, which is the clear direction of the JavaScript language. The mechanics are better than CommonJS

CommonJS is a temporary solution proposed before the ES specification. It is a special traditional format.

In contrast, the ES module allows for static analysis, optimizations like tree-shaking, and advanced features such as circular references and dynamic binding

Tree-shaking, also known as “live code inclusion,” is the process of removing code that is not actually used in a given project, but it can be much more efficient.

Build Tool comparison

Packaging tools volume Injecting code code spliting dynamic import Tree-shaking
webpack large more
rollup small less

Webpack is a powerful bundle building tool that can handle various types of files through the Loader mechanism. Good code splitting and dynamic import support make Webpack a versatile packaging tool for applications, single page applications.

However, because of its relatively large packaging volume, more code injection, and not good tree-shaking, Library packaging is not as streamlined as rollup packaging.

configuration

Rollup positioning is a lightweight build tool that is relatively simple to configure, but because rollup-plugin-CommonJS does not support CommonJs, Babel translation needs to be configured when configuring rollup-plugin-CommonJS to convert CommmonJS to ES module mode

Because Babel 7+ upgrade has big changes and namespace changes, most tutorials in the market are not clear enough, and basically stay in Babel 6 configuration, resulting in plugin CommonJS SyntaxError: Unexpected Token

We’ll focus on this later in this article, analyzing the Babel 7+ configuration and the role of individual Presets and plugins.

Install a rollup

npm install --save-dev rollup
Copy the code

The configuration file

Create the rollup.config.js file in the project root directory.

Rollup configuration is simple, generally includes input, output, plugins, external

Configuration Item Reference

This is a simple configuration file

export default {
  input: 'src/index.js'.output: {
    name: 'amapUpper'.file: 'dist/amapUpper.js'.format: 'umd' // Compatible mode
  },
  external: ['@amap/amap-jsapi-loader'].// Configure whether the imported package should be packaged. The configured package will be ignored and not packaged into our program
  plugins: []};Copy the code

You can also do this when your profile requires multiple packaging policies

export default [{
  input: 'main-a.js'.output: {
    file: 'dist/bundle-a.js'.format: 'cjs'}}, {input: 'main-b.js'.output: [{file: 'dist/bundle-b1.js'.format: 'cjs'
    },
    {
      file: 'dist/bundle-b2.js'.format: 'es'}}]]Copy the code

You can also use multiple configuration files, using –config to use configuration files

# pass a custom config file location to Rollup
rollup --config my.config.js
Copy the code

::: DANGER uses umD mode must specify Name for UMD export ::

Configure the rollup plug-in

Plugin for gollup configuration is similar to Babel, which has been transplanted to @rollup. In the official one-stop configuration shop, you can download the required plug-in, which is more conducive to long-term maintenance and can reduce the cost of maintenance learning.

@plugin link address

What is a plug-in

The Rollup Plugin is an object that follows the rollup plug-in specification and is typically implemented by returning an object from a factory function

A simple example:

export default function myExample () {
  return {
    name: 'my-example'.// this name will show up in warnings and errors
    resolveId ( source ) {
      if (source === 'virtual-module') {
        return source; // this signals that rollup should not ask other plugins or check the file system to find this id
      }
      return null; // other ids should be handled as usually
    },
    load ( id ) {
      if (id === 'virtual-module') {
        return 'export default "This is virtual!" '; // the source code for "virtual-module"
      }
      return null; // other ids should be handled as usually}}; }Copy the code

The plug-in is then referenced in the configuration file, and in plugins, the object returned by the execution is passed in

import myExample from 'myExample'


plugins: [ myExample() ]
Copy the code

The specification that the plug-in object follows

A Rollup plugin is an object with one or more of the properties, build hooks, and output generation hooks

  • properties
  • Build hooks Build hooks
  • Output generation hooks Output hooks

Order of plug-in execution

If you are familiar with webPack Loader, you should know that loader actually executes from right to left and from bottom up. The analogy to WebPack Loader is a false analogy. The plugin mechanism for rollup is actually executed from left to right, top-down.

A test example

// rollup.config.js
function myExample1() {
  return {
    name: 'my-example1'.// this name will show up in warnings and errors
    resolveId(source) {
      console.log('111 resolve_______________-------------------------------------------');
      return null; // other ids should be handled as usually
    },
    load(id) {
      console.log('111 load_______________-------------------------------------------');
      return null; // other ids should be handled as usually}}; }function myExample2() {
  return {
    name: 'my-example1'.// this name will show up in warnings and errors
    resolveId(source) {
      console.log('222 resolve_______________-------------------------------------------');
      return null; // other ids should be handled as usually
    },
    load(id) {
      console.log('222 load_______________-------------------------------------------');
      return null; // other ids should be handled as usually}}; }export default {
  input: 'src/index.js'.output: {
    name: 'test'.file: 'dist/test.js'.format: 'umd'
  },
  plugins: [
    myExample1(),    
    myExample2()
  ]
};

Copy the code

As you can see, the Load and resolve hook functions are executed from left to right, top-down.

Configure common plug-ins

The following describes the plug-ins needed for normal packaging, as well as general configuration.

  • @rollup/plugin-json rollup-plugin-json
  • @rollup/plugin-commonjs rollup-plugin-commonjs
  • @rollup/plugin-node-resolverollup-plugin-node-resolve
  • rollup-plugin-terser

First, you need to install these plug-ins as development dependencies

npm i @rollup/plugin-json -D
npm i @rollup/plugin-commonjs -D
npm i @rollup/plugin-node-resolve -D
npm i rollup-plugin-terser -D
Copy the code

You then need to reference the configuration file

import json from '@rollup/plugin-json';
import commonjs from '@rollup/plugin-commonjs';
import nodeResolve from '@rollup/plugin-node-resolve';
import babel from 'rollup-plugin-babel';
import { terser } from 'rollup-plugin-terser';

export default{...plugins: [
    json(),
    terser(),
    nodeResolve(),
    commonjs(),
    babel({
      exclude: The '*'.// Exclude files under node_modules
      runtimeHelpers: true // Prevent multiple packaging helper functions from being generated})]};Copy the code

The problem summary

Commonjs plugin and Babel7 + configuration

In the process of setting up the package JS configuration with rollup, the plug-in used is not the long-term maintenance version provided by the official one-stop plug-in, and I encountered the rollup-plugin-commonJS plug-in package error

There are two solutions to the SyntaxError thrown using a package of the rollup-plugin-commonJS plug-in that has been abandoned for maintenance. Plan 2 is recommended.

Solution one: Configure Babel

A lot of information found, should be the Babel configuration problem, mainly divided into:

  • babelConfiguration problem
  • babelTranslation execution order problem

The commonJS plugin library has been moved to @rollup/plugin-commonjs for maintenance, resulting in the absence of some post-translation helper functions and attributes in the non-long-term maintenance version, causing an exception to be thrown.

So you need Babel to help you compile to properly execute the CommonJS plug-in.

Some problems with Babel configuration

Most of the Babel tutorials in the market do not explain this, and the installation of Babel components in the tutorials does not specify the version. This may actually result in the installation of the 7+ version of the Babel core library, and the installation of the plugin presets under babel-plugins-*** that were abandoned for maintenance, or something like that. Can lead to a series of problems.

And notice this sign here, this sign, this is unique to Babel7, babel6 doesn’t even exist, there’s a lot of code out there that’s based on 6 so be careful, NPM install i-s@babel \cli NPM install i-s@babel \cli NPM install i-s@babel \cli The original Babel-XX package is uniformly migrated to the Babel domain – the domain is identified by the @ symbol

See the use of Babel 7 mentioned at the beginning of this article for personal understanding

configuration

Since @rollup/plugin-babel is used here to perform Babel translation, there is no need to install @babel/ CLI command-line tools.

First we need to install:

  • Babel core packages@babel/core
  • Babel default package@babel/preset-env
  • Unified modular helper@babel/runtime
  • Helper automation introduction tools@babel/plugin-transform-runtime
npm i -D @babel/core
npm i -D @babel/preset-env
npm i -D @babel/runtime
npm i -D @babel/plugin-transform-runtime
Copy the code

Then create a configuration file for. Babelrc in the project root directory

{
  "presets": [["@babel/preset-env",
      {
        "modules": false."targets": {
          "browsers": [
            "1%" >."last 2 versions"."not ie <= 8"]}}]],"plugins": ["@babel/plugin-transform-runtime"]}Copy the code

Then if you are using the rollup-plugin-commonJS emergency maintenance version of the plugin, because of the dependency on Babel, you need to:

Introduce the Babel plug-in before the CommonJS plug-in, and configure the files and directories that need to match the compilation. And compile configuration

// rollup.config.js
export default {
  input: 'src/index.js'.output: {
    name: 'amapUpper'.file: 'dist/amapUpper.js'.format: 'umd'
  },
  plugins: [
    babel({
      exclude: '/node_modules/**'.// Exclude files under node_modules
      runtimeHelpers: true // Generate a unified helper corresponding to the plugin-transform-Runtime plug-in.
    }),
    commonjs()
  ]
};
Copy the code

Solution 2

Use the plugins in rollup’s new official post-mobile one-stop plugin library

rollup@plugin link address

After using the new plugin library, Babel still needs to be configured, but the commonJS plugin relies on Babel.

Babel is actually addressing the differences between browsers and engines. So for better support, you need to have a good Babel configuration.

this over

Welcome everyone to praise and correct mistakes.