“This is the 23rd day of my participation in the First Challenge 2022. For details: First Challenge 2022”

preface

This article will build a Rollup package project step by step, and introduce the role of plug-ins in Rollup. Finally, it will show you the simplest effect of printing different packages from different command lines.

What is Rollup?

Rollup is a JavaScript module wrapper that compiles small pieces of code into large, complex pieces

The more common ones are Webpack and Esbuild. Rollup is also designed to package the code we have written for multiple modules into a specific format that we want it to run in a browser environment.

We can use:

npm install --global rollup
Copy the code

Rollup can be successfully packaged after some basic configuration. See the official documentation for the tutorial:

rollup.js (rollupjs.org)

Basic use of Rollup

  1. First we need to create a new test project calledmy-rollup, the use of:
npm init
Copy the code

Initialize the project and install the rollup dependency.

npm install rollup --global
Copy the code

This is the global Rollup installation, and since we will need to customize the Rollup installation later, using the Rollup API, we will need to install Rollup into node_module.

npm install rollup
Copy the code
  1. Next, we use two small files to test Rollup’s packaging capabilities

Create a SRC folder under the directory

// src/main.js
import foo from './foo.js';
export default function () {
    console.log(foo);
}
Copy the code
// src/foo.js
export default "hello world!";
Copy the code
  1. The package is then packaged using Rollup, either by passing in the package parameters on the command line
rollup src/main.js -o bundle.js -f cjs
Copy the code

Bundle. js file was successfully added to the directory, and node tested the package result:

PS D:\my-rollup> node
Welcome to Node.js v1417.6..
Type ".help" for more information.
> var bundle = require('./bundle.js')
undefined
> bundle()
hello world!
Copy the code

Packing successful.

  1. In addition to passing in parameters from the command line, we can also package configuration through configuration files, create a rollup.config.js file, and add simple package parameters.
// rollup.config.js
export default {
    input: 'src/main.js'.output: {
        file: 'bundle.js'.format: 'cjs'}};Copy the code
  1. This can be packaged through configuration files:
rollup -c
Copy the code

Rollup plugin used

As our project gets bigger and bigger, our packaging requirements may not be limited to simple JS files, but may include various files, at which point we will need to use Rollup plug-ins

For plugins, Rollup packs an error warning if you use a file that Rollup doesn’t know about, such as when I introduced a JSON file in my project:

import { version, name } from ".. /package.json";

export default function () {
  console.log("version " + version);
  console.log("name " + name);
}
Copy the code

Then packaging will report an error

He told us we needed to use rollup-plugin-json, so let’s install it and try it out.

  1. Install plugin dependencies:
npm install --save-dev rollup-plugin-json
Copy the code
  1. Introduce the plug-in we downloaded in the Rollup configuration file
// rollup.config.js
import json from "rollup-plugin-json";

export default {
  input: "src/main.js".output: {
    file: "bundle.js".format: "cjs",},plugins: [json()],
};
Copy the code
  1. If the package is successful, go to the package file bundle.js

We successfully read the data in the JSON file and only get what we want. That’s what the rollup-plugin-json plugin does. Instead of getting the entire JSON object, we get the required attributes.

Rollup also has a number of plugins, such as package CSS files, TS files, IMG files, etc., which can be installed according to the requirements of the project.

Implement custom packaging through apis

Simple use of the API

Rollup can be invoked not only through a command line interface with an optional configuration file, but also through a JavaScript API.

That’s why we installed Rollup in the project above, Rollup exposes an object to us, right

const rollup = require("rollup");
console.log("rollup", rollup);
Copy the code

As you can see, this object is exposing some methods and properties, and what we’re going to use is rollup, which is a method call that will do the packaging, and we can pass in an object, and that object will be our configuration object.

Then we configure our “scripts” so that we can debug later. When we call bulid, we run our bulid.js directly to package the project

"scripts": {
  "build": "node scripts/build.js"
},
Copy the code

Create a new scrpit folder under the project to store the build.js package module and add other configurations later

Then the rollup method under rollup calls the package method and returns a Promise object with a write method on it. Rollup passes in the package-related input configuration:

const inputOptions = {
// Core parameters
input, // Only mandatory parameter
external,
plugins,

// Advanced parameters
onwarn,
cache,

// Danger parameters
acorn,
context,
moduleContext,
legacy
};
Copy the code

The write method passes in the configuration object needed for the output:

const outputOptions = {
// Core parameters
file,   // This parameter is mandatory if bundle.write exists
format, / / required
name,
globals,

// Advanced parameters
paths,
banner,
footer,
intro,
outro,
sourcemap,
sourcemapFile,
interop,

// Danger zone
exports,
amd,
indent
strict
};
Copy the code

With these two methods, we can easily use the API to package

const option = {
  inputOptions: {
    input: "src/main.js",},outputOptions: {
    file: "./bundle.js".format: "cjs",}};const rollup = require("rollup");
console.log("rollup", rollup);

async function build() {
  const outputOptions = option.outputOptions;
  const inputOptions = option.inputOptions;
  const bundle = await rollup.rollup(inputOptions);
  await bundle.write(outputOptions);
}

build();
Copy the code

When run, you can generate bundle.js in the directory just like normal command line packaging

Customize packaging options using the API

Since we can package by calling the “scripts” command, we can also add the relevant configuration options to “scripts” and then call different packaging options for different parameters. Here is a simple implementation of a package output different file name example.

  1. Configure our multiple options. Since there are multiple different configuration options to implement, you need multiple different configuration objects to implement various customizations.
const option1 = {
  inputOptions: {
    input: "src/main.js",},outputOptions: {
    file: "./bundle1.js".format: "cjs",}};const option2 = {
  inputOptions: {
    input: "src/main.js",},outputOptions: {
    file: "./bundle2.js".format: "cjs",}};Copy the code
  1. Then we implement the second packaging command and pass in the identity we have decided:
"scripts": {
  "build": "node scripts/bulid.js"."build:two": "npm run build -- use-option2"
},
Copy the code
  1. Get the command line input from process.argv in the build.js package function, so you can determine which package command is executed:
if (process.argv[2] = ="use option2") {
    option = option2;
} else {
    option = option1;
}
Copy the code
  1. Then we run different commands to generate different packages under the file:

  1. This allows us to implement a simple custom command for different packaging.

Then we can configure more packaging parameters according to our own needs, so that we can make the packaging become more flexible, according to the different needs, hit different versions of the package.

conclusion

In many excellent projects, is also the use of similar packaging method to play different needs of the package, such as our most common VUE project is similar form, next we will talk about in VUE, it is according to the different configuration, to flexibly implement packaging customization.