Rollup Modular Packaging Tool

Chapter 0: Pre-knowledge

0.1 ES standard modular specification – Overview

Historically, JavaScript has not had a module system that allows you to break up a large program into small interdependent files and put them together in a simple way. Other languages have this functionality, such as Ruby’s require, Python’s import, and even CSS has @import, but JavaScript has no support for any of this, which is a huge barrier to developing large, complex projects.

Prior to ES6, there were several module loading schemes developed by the community, the most important being CommonJS and AMD. The former is used for servers and the latter for browsers. ES6 in the language standard level, the realization of module function, and the implementation is quite simple, can completely replace CommonJS and AMD specifications, become a common browser and server module solution.

The ES6 module is designed to be as static as possible, so that the module dependencies, as well as the input and output variables, can be determined at compile time. Both CommonJS and AMD modules can only determine these things at runtime. For example, a CommonJS module is an object, and you have to look for object properties when you enter it.

A module is an independent file. All variables inside the file are not available externally.

If you want outsiders to be able to read a variable inside a module, you must export it using the export keyword. If you want content exported by other modules, you must import it using import.

0.2 the import (Importing)

Imported values cannot be reassigned, although imported objects and arrays can be modified (the export module, as well as any other imports, will be affected by this change). In this case, they behave like const declarations.

0.2.1 Named Imports

Imports a specific project with its original name from the source module.

import  { something } from './module.js';
Copy the code

Import specific items from the source module and specify custom names when importing.

import { something as somethingElse } from './module.js';
Copy the code

0.2.2 Namespace Imports (Namespace Imports)

All content in the source module is imported as objects and all named exports of the source module are exposed as properties and methods. The default export is excluded from this object.

import as module from './module.js'
Copy the code

The “something” example above will be appended to the import object as a property. “Module. Something.”

0.2.3 Default Import (Default Import)

Import the default export of source files

import something from './module.js';
Copy the code

0.2.4 Empty Import (Empty Import)

Load the module code, but do not create any new objects.

import  './module.js';
Copy the code

This is useful for polyfills, or when the primary purpose of the imported code is to relate to stereotypes.

0.3 export (Exporting)

0.3.1 Named exports

Export the specified declared value:

var something = true;
export { something };
Copy the code

Rename when exporting:

export { something as somethingElse };
Copy the code

Export immediately after declaration:

// This can work with 'var', 'let', 'const', 'class', and 'function'
export var something = true;
Copy the code

0.3.2 Default Export (Default Export)

Export a value as the default export for the source module:

export default  something;
Copy the code

This is recommended only if the source module has only one export.

It is bad practice to combine default and named exports in the same module, although it is permitted by the specification.

Chapter 1 Introduction to Rollup

1.1 Overview (Overview)

Rollup is a JavaScript module wrapper that compiles small pieces of code into large, complex pieces. Rollup uses the new ES Module standard for code modules rather than previous community modularity schemes such as CommonJS and AMD. The ES6 module has been implemented by modern browsers. In 2020, the author of Vue released Vite, which is defined as the next generation of front-end development and build tools. The purpose is to replace various build tools that rely on Webpack packaging, while Vite’s modular tools use Rollup.

1.2 Quick Start

Use NPM install –global rollup to install and run rollup –help to see the available options and parameters.

In the help message prompt: Usage: Rollup [options]

rollup [options]

Js and message.js files are imported using ES6 modularization syntax, and the data content exported from the two files is used in mian.

// ======= index.js ============
import msg from './message'
import {names} from './user'

console.log(names())
console.log(msg)
console.log('Rollup Test Code')

// ======== message.js ===========

export default {
  hi: 'Hey '
}

// ======== user.js ===========

export const names = () = > {
  console.log('xiling')}export const ages = () = > {
  console.log(Awesome!)}Copy the code

The command line terminal runs rollup index.js

$ rollup index.jsIndex. Js to stdout... var msg = { hi: 'Hey ' }; const names = () => { console.log('xiling'); }; console.log(names()); console.log(msg); console.log('Rollup Test Code');Copy the code

In the command terminal, we can see that the compiled code is printed after the final package. What we need is to package the small file code into a large file. To achieve this effect, we need to add the specified command parameters to the command: Rollup index.js –file bundle.js generates bundle.js as follows:

var msg = {
  hi: 'Hey '
};

const names = () = > {
  console.log('xiling');
};

console.log(names());
console.log(msg);
console.log('Rollup Test Code');
Copy the code

As you can see, the packaged code is very neat, piecing together the code that needs to be run in order. Note that only the code that needs to be run is kept. This is the tree-shaking feature that Rollup first introduced, and has since been introduced by almost every packaging tool reference.

What is tree-shaking? The basic principle is very simple, Rollup statically analyzes the imports in the code during packaging, introduces only the most basic and minimal code, and excludes any code that is not actually used. So you can generate libraries and applications that are lightweight, fast, and low-complexity.

1.3 Configuration File

We typically use Rollup on the command line. You can also provide a configuration file (optional) to simplify command-line operations and enable Rollup’s advanced features. The configuration file is an ES6 module that exposes an object that contains some of the options required for Rollup. Normally, we call this configuration file rollup.config.js and it is usually located at the root of the project;

Note: Rollup handles configuration files itself, so you can use the Export Default syntax — the code is not compiled by Babel or the like, so you can only use the ES2015 syntax supported by the node.js version you are using.

Configuration options list: https://www.rollupjs.com/guide/big-list-of-options

// rollup.config.js
export default {
  // The entry point of the package (e.g. your main.js or index.js)
  input:'index.js'.// Export configuration
  output: {file:'budle.js'.// Package to that file
    format:'esm' // The format of the generated package}}Copy the code

Input: input [string]: ‘index.js’ The entry point of this package (e.g. your main.js or app.js or index.js)

Output: output [object]:{}

Output.file [string]: the file to be written by ‘bundle.js’. Can also be used to generate sourcemaps, if applicable

Format [string] :’iife’ generated packet format. One of the following:

  • amd– Asynchronous module definition for module loaders like RequireJS
  • cjs— CommonJS for Node and Browserify/Webpack
  • esm– Save the software package as an ES module file, which can be passed in modern browsers<script type=module>Tags introduced
  • iife– an autoexecute function, suitable as<script>The label. (If you’re creating a bundle for your application, you might want to use it because it makes the file size smaller.)
  • umd– Generic module definition toamd.cjsiifeAs a whole
  • system– SystemJS loader format

If you want to use Rollup configuration files, add –config or -c to the command line

If a different configuration is required, you can also specify a configuration file different from the default rollup.config.js file:

rollup --config rollup.config.dev.js
rollup --config rollup.config.prod.js
Copy the code

Chapter 2 uses plug-ins

2.1 Understand plug-ins and basic use of plug-ins

So far, we have created a simple bundle from an entry file and a module through a relative path. As you build more complex bundles, you often need more flexibility — importing modules installed by NPM, compiling code through Babel, working with JSON files, and so on.

To do this, plugins can be used to change the behavior of Rollup during critical packaging processes;

A Rollup has a very rich plug-in system, can go to the plugin list: https://github.com/rollup/awesome have a look at;

Here we will use the rollup-plugin-json plug-in to enable rollup to read the data in the JSON file.

Install rollup-plugin-json as a development dependency, because the code doesn’t rely on the plug-in for actual execution — just for packaging:

npm install rollup-plugin-json -D 
Copy the code

Edit the rollup.config.js file and add the JSON plugin:

// Import plug-ins directly using ES module
import json from 'rollup-plugin-json';

export default {
  input:'./src/index.js'.output: {file:'./dist/budle.js'.format:'iife',},// Plugins export a function, call the function directly,
  // Note that the result of the call is given directly to the plugin array
  plugins: [ json() ]
}
Copy the code

Change the code for index.js to read data from package.json:

import msg from './message'
import { names } from './user'

import { name, version } from '.. /package.json';
console.log('Project Name:${name}, Project version:${version}`)

console.log(names())
console.log(msg)
console.log('Rollup Test Code')

Copy the code

The packaged code keeps only name and version, which is where tree-shaking comes in.

Author: Xiling Laoshi

Reference:

Wangdoc.com/es6/module….

cn.vitejs.dev/

www.rollupjs.com/