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

Why is Rollup generally good for packaging JS libraries?

  • The code packaged by rollup will be smaller and more concise than webpack, without too much redundant code.
  • Rollup also has good support for ES module output and iIFE format packaging

So rollup is better suited to building a component library. This article will not extend the rollup and Webpack comparisons.

Write a TypeSript component

Components are developed in TypeScript, so build the basic TypeScript development environment first

NPM init -yes // generates basic package.json NPM install -g typescript tsc-init // generates tsconfig.jsonCopy the code

Create a SRC file in the root directory and create an utils.ts file to write the component content, where the file directory looks like this

├─ SRC │ ├─ ├─ download.txt ├─ ├.txtCopy the code

Start by writing a random component with a method to set and get cookies

/* utils.js */

export const setCookie = (key: string, value: string) => {
  document.cookie = `${key}=${value}; `; };export const getCookie = (key: string): string => {
  const items: string[] = document.cookie.split('; ');
  for (let i = 0; i < items.length; i += 1) {
    const item: string[] = items[i].split('=');
    if (key === item[0] && item.length === 2) {
      returndecodeURIComponent(item[1]); }}return ' ';
};

Copy the code

Modify the tsconfig configuration

/* tsconfig.json */

{
  "compilerOptions": {
    "target": "es6"."lib": ["dom"."esnext"]."outDir": "lib"."declaration": true."module": "esnext"."moduleResolution": "node"."jsx": "react"
  },
  "include": ["src"]} / / attach the configuration document: https://www.tslang.cn/docs/handbook/compiler-options.htmlCopy the code

The TSC command will compile the tsconfig.json configuration to generate a package named lib and separate the types

Build UMD packages using Rollup

UMD is called the Universal Module Definition, which is a javascript Universal Module Definition specification that allows your modules to work in all javascript environments.

Install rollup and parse the TS package first

npm i -D rollup rollup-plugin-typescript2 typescript
Copy the code

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

/* rollup.config.js */

import typescript from 'rollup-plugin-typescript2';
import { version } from './package.json';

export default {
  input: 'src/utils.ts'// output: {name:'my_utils'// UmD must have the name attribute as a global variable to access the package result file: 'dist/@${version}/index.js`,
    format: 'umd',
    sourcemap: true,
  },
  plugins: [
    typescript({
      tsconfigOverride: {
        compilerOptions: {
          declaration: false},},}),],};Copy the code

Rollup -c: rollup -c: rollup -c

Babel compilation

Install a series of Babel packages

npm i -D @babel/core @babel/plugin-transform-runtime @babel/preset-env @rollup/plugin-babel @babel/preset-typescript
Copy the code

Create a.babelrc file to configure Babel

{
  "presets": [["@babel/preset-env",
      {
        "modules": false."loose": true."targets": {
          "browsers": "> 1%, IE 11, not op_mini all, not dead"."node": 8}}], ["@babel/preset-typeScript"]]}Copy the code

Introduce Babel in rollup.config.js

import { babel } from '@rollup/plugin-babel';
plugins:[
    babel({
      extensions: [".js".".ts"],
      exclude: "node_modules/**",
      babelHelpers: 'bundled'}),]Copy the code

Execute rollup -c to compile

The lib package is packaged by the TSC command and not processed by Babel. Take care of it

npm install @babel/cli -D
Copy the code

Babel lib –out-dir lib

The compression

Install the compression plug-in

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

Add the plug-in’s final rollup.config.js to rollup.config.js

/* rollup.config.js */

import typescript from 'rollup-plugin-typescript2';
import { babel } from '@rollup/plugin-babel';
import { terser } from 'rollup-plugin-terser';
import { version } from './package.json';

export default {
  input: 'src/utils.ts',
  output: {
    name: 'my_utils',
    file: `dist/@${version}/index.js`,
    format: 'umd',
    sourcemap: true,
  },
  plugins: [
    typescript({
      tsconfigOverride: {
        compilerOptions: {
          declaration: false,
        },
      },
    }),
    babel({
      extensions: [".js".".ts"],
      exclude: "node_modules/**",
      babelHelpers: 'bundled'
    }),
    terser(),
  ],
};
Copy the code

And then just finishing up

Delete the lib folder and then execute TSC to separate the TS files from xxx.D. ts files and JS files, then go through Babel to compile the lib folder

The purpose of TSC is to get type files, which can be introduced in TS development

Delete the dist folder and rollup the UMD file

Here’s another amway plugin rimraf when repackaged. Rimraf [ …] Json, add the script “build” to scripts under package.json: “Rimraf /lib/ && TSC && Babel lib –out-dir lib && rimraf /dist/ && rollup -c” Then execute build command

Dist /@1.0.0/index.js”>

my_utils
rollup.config.js -> output
name

Github address: github.com/Coffee-C/ro…