Currently, the mainstream front-end frameworks vue and React use rollup to package. In order to explore the mystery of Rollup, let’s explore step by step, and build a library packaging scaffolding based on Rollup, to release their own libraries and components.

preface

The rollup article was written because I recently wanted to standardize the business processes and architecture of front-end development and provide an internal public component library and tool library for the team to use. After reviewing a lot of materials and comparing the advantages and disadvantages of WebPack and Rollup, rollup was chosen as the packaging tool, and we finally implemented the installation of our component libraries and tool libraries via NPM:

/ / installation
npm install @xuxi/tools
/ / use
import { sleep } from '@xuxi/tools'
Copy the code

Let’s step through the configuration process and best practices of disk rollup.

Introduce a rollup

Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application. It uses the new standardized format for code modules included in the ES6 revision of JavaScript, instead of previous idiosyncratic solutions such as CommonJS and AMD.

Rollup is a JavaScript module wrapper that compiles small pieces of code into larger complex pieces, such as a library or application. Rollup uses new standardized formats for code modules that are included in the ES6 version of JavaScript, rather than special solutions like CommonJS and AMD.

The best part of Rollup is tree-shaking, which is the ability to statically analyze imports in code and exclude any unused code. This allowed us to build on existing tools and modules without adding additional dependencies or inflating the project’s size. Tree-shaking is possible if you do it with WebPack, but the code that needs to be configured and packaged is very bloated, so rollup is more suitable for library files and UI components.

Build the library and pack the scaffolding

1. Introduction to a rollup

First let’s install rollup:

npm i rollup -g
Copy the code

Then create a project locally:

mkdir -p my-project
cd my-project
Copy the code

Next we create an entry and write the following code:

// src/main.js
import say from './say.js';
export { say }

// src/say.js
export default function(name){ 
    console.log(name) 
};
Copy the code

With the basic code ready, we write rollup’s configuration file (rollup.config.js in the root directory) :

// rollup.config.js
export default {
  input: 'src/main.js'.output: {
    file: 'bundle.js'.format: 'cjs'}};Copy the code

In this way, we perform at the terminal:

// --config or -c to use the configuration file rollup -cCopy the code

This generates a bundle.js file in the further directory, which is the bundle we want. We can also use package.json to set the packaging configuration and NPM run XXX to package and test the code.

2. Use the rollup plug-in

For more flexible packaging of libraries, we can configure the Rollup plug-in. Some useful plug-ins are:

  • Rollup-plugin-nod-resolve — helps Rollup find external modules and import them
  • Rollup-plugin-commonjs — converts commonJS modules to ES2015 for rollup processing
  • Rollup-plugin-babel – allows us to write code using new ES6 features
  • Rollup-plugin-terser — compresses JS code, including ES6 code compression
  • Rollup-plugin-eslint — js code detection

These plug-ins are sufficient to package a library, but if you want to implement code for components like React, there are many more plug-ins available, which I won’t cover here.

We can use this plugin configuration similar to webPack:

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

export default[{input: 'src/main.js'.output: {
			name: 'timeout'.file: '/lib/tool.js'.format: 'umd'
		},
		plugins: [
			resolve(),  // This Rollup will find 'ms'
			commonjs(), // This Rollup converts' ms' into an ES module
			eslint(),
			babel(),
			terser()
		]
	}
];
Copy the code

Isn’t that easy? Personally, it is much simpler than webPack configuration. With the above configuration, you can achieve basic javascript file packaging, but it is not robust enough, so let’s step through the details of the configuration.

3. Use Babel to compile ES6 code

First, let’s install Babel related modules:

npm i core-js @babel/core @babel/preset-env @babel/plugin-transform-runtime
Copy the code

Then set the. Babelrc file

{
  "presets": [["@babel/preset-env",
      {
        "modules": false."useBuiltIns": "usage"."corejs": "2.6.10"."targets": {
          "ie": 10}}]],"plugins": [
      // Solve the problem of using the same code in multiple places, resulting in duplicate packaging
      ["@babel/plugin-transform-runtime"]],"ignore": [
      "node_modules/**"]}Copy the code

@babel/preset-env automatically converts ES2015+ code to ES5 based on the configured target browser or runtime environment. Note that 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.

To solve the problem of duplicate packaging using the same code in multiple places, we need to configure @babel/ plugin-transform-Runtime in.babelrc’s plugins, and we need to modify rollup’s configuration file:

babel({
  exclude: 'node_modules/**'.// Prevent files from being packaged under node_modules
  runtimeHelpers: true.// Make plugin-transform-Runtime effective
}),
Copy the code

If you’re unfamiliar with Babel, check out my previous Webpack article or check out the website.

4. Distinguish between test and development environments

We can configure different execution scripts and environment variables in package.json to do different configurations for development and production:

// package.json
"scripts": {
    "build": "NODE_ENV=production rollup -c"."dev": "rollup -c -w"."test": "node test/test.js"
  },
Copy the code

We can manually export NODE_ENV for production and development to distinguish between production and development environments, and then get the parameters from process.env.node_env in the code. Here we mainly use the setting to not compress code in the development environment:

constisDev = process.env.NODE_ENV ! = ='production';
// ...
plugins: [
  !isDev && terser()
]
Copy the code

Use ESLint for code detection

We can use the rollup-plugin-esLint configuration mentioned above:

eslint({
    throwOnError: true.throwOnWarning: true.include: ['src/**'].exclude: ['node_modules/**']})Copy the code

Then create.eslintrc.js to configure specific checks according to your style:

module.exports = {
    "env": {
        "browser": true."es6": true."node": true
    },
    "extends": "eslint:recommended"."globals": {
        "Atomics": "readonly"."SharedArrayBuffer": "readonly"."ENV": true
    },
    "parserOptions": {
        "ecmaVersion": 2018."sourceType": "module"
    },
    "rules": {
        "linebreak-style": [
          "error"."unix"]."quotes": [
          "error"."single"]}};Copy the code

Detailed ESLint configuration can be found on the esLint website.

5. External properties

With rollup packaging, we need to use third-party libraries such as Lodash in our libraries, but we don’t want jquery in the resulting package. At this point we need to use the external attribute. For example, we used lodash,

import _ from 'lodash'

// rollup.config.js
{
    input: 'src/main.js'.external: ['lodash'].globals: {
        lodash: '_'
    },
    output: [{file: pkg.main, format: 'cjs' },
	{ file: pkg.module, format: 'es'}}]Copy the code

6. Export the mode

We can export our code into commonJS modules, ES modules, and browser-recognized modules by setting:

{
  input: 'src/main.js'.external: ['ms'].output: [{file: pkg.main, format: 'cjs' },
	{ file: pkg.module, format: 'es' },
	{ file: pkg.module, format: 'umd'}}]Copy the code

Published to the NPM

If you have not registered an NPM account before, you can configure it as follows:

npm adduser
Copy the code

Then enter your username, mailbox, password, and publish using NPM Publish. Here’s the package configuration file, package.json:

{
  "name": "@alex_xu/time"."version": "1.0.0"."description": "common use js time lib"."main": "dist/tool.cjs.js"."module": "dist/time.esm.js"."browser": "dist/time.umd.js"."author": "alex_xu"."homepage": "https://github.com/MrXujiang/timeout_rollup"."keywords": [
    "tools"."javascript"."library"."time"]."dependencies": {
    // ...
  },
  "devDependencies": {
    // ...
  },
  "scripts": {
    "build": "NODE_ENV=production rollup -c"."dev": "rollup -c -w"."test": "node test/test.js"."pretest": "npm run build"
  },
  "files": [
    "dist"]}Copy the code

The name is the name of the package. You can either write the package name, such as loadash, or add a domain, such as @koa/router, where the @ is followed by your NPM registered user name. Key is the key of the package.

After release, we can install it in a way similar to the following:

npm install @alex_xu/time
/ / use
import { sleep } from '@alex_xu/time'
/ / or
const { sleep } = requrie('@alex_xu/time')
Copy the code

Here is a screenshot of the installation:

The last

The full profile has been posted to Github at github.com/MrXujiang/t…

If you want to know more about webpack, gulp, CSS3, javascript, nodeJS, Canvas and other front-end knowledge and actual practice, welcome to join us in the public account “Interesting talk front-end” to learn and discuss, and jointly explore the boundary of the front-end.

More recommended

  • A picture shows you how to play vue-Cli3 quickly
  • Vue Advanced Advanced series – Play with Vue and vuex in typescript
  • Learn es6+ new features and es6 core grammar check quickly
  • Implementing a CMS full stack project from 0 to 1 based on nodeJS (Part 1)
  • Implementing a CMS full stack project from 0 to 1 based on nodeJS (middle)
  • Implement a CMS full stack project from 0 to 1 based on nodeJS (Part 2)
  • Implement server startup details for a CMS full stack project from 0 to 1 based on nodeJS
  • Developing travel List with Angular8 and Baidu Maps API
  • “Javascript advanced programming” core knowledge summary
  • With CSS3 to achieve stunning interviewers background that background animation (advanced source)
  • Write a mock data server using nodeJS in 5 minutes
  • Teach you to use 200 lines of code to write a love bean spell H5 small game (with source code)