Use TS+rollup to build an npm tool library

Table of contents

foreword

Why Not TS?

Environment build

tool configuration

Write code

Packaging & Publishing

Summarize

sample code

Relevant information


foreword

Speaking of Rollup, you may be familiar with it. It is a JS module packager, suitable for packaging tool libraries and components, and merging multiple modules into a single file. It is different from Webpack, Browserify, etc. It is more friendly to smaller and faster libraries. In addition, he can generate output formats such as ESM, CommonJS, AMD and UMD, and supports TS input, and can check TS type and code

Why Not TS?

I am also updating TS articles recently . tsc can directly compile TS into specified JS, so why not use TS compilation directly?

In fact, when writing the toolkit in the early days , TS compilation was used. Later, in order to be compatible with different environments, this article was produced to adapt the early version of Node and the new version. However, problems occurred when using UMD:

We know that when compiling with "module": "UMD" in tsconfig, the following code is not generated like the code in the official document

(function (root, factory) {
    if (typeof define === "function" && define.amd) {
        define(["libName"], factory);
    } else if (typeof module === "object" && module.exports) {
        module.exports = factory(require("libName"));
    } else {
        root.returnExports = factory(root.libName);
    }
}(this, function (b) {
   
   

Instead, the following code is generated, which is only adapted for cjs and amd, so that the corresponding statement cannot be obtained in the global environment. Someone has proposed this a long time ago

if (typeof module === "object" && typeof module.exports === "object")
...
else if (typeof define === "function" && define.amd)
...

This is not very friendly to the browser's script form. In addition to this problem, the .js suffix will not be automatically generated when the file generated by ESM packaging is imported into the module. It needs to be added manually every time .

These questions drove me to use the packaging tool

rollup can solve the above problems and make code packaging more standardized and unified

Environment build

Refer to this article to configure the npm environment, and refer to this article to install TS

Initialize with pnpm init in tools repository or new folder

Then use pnpm i --save-dev @rollup/plugin-alias @rollup/plugin-json @rollup/plugin-node-resolve @rollup/plugin-typescript rollup rollup-plugin-terser tslib typescript to install rollup and some common development dependencies

in

  • @rollup/plugin-alias: Use an alias to refer to modules in your code. Here we can use it to introduce the .js suffix to ESM
  • @rollup/plugin-node-resolve: resolve dependencies of third-party modules
  • @rollup/plugin-typescript: Supports packaging of TypeScript code
  • rollup: module bundler
  • rollup-plugin-terser: Terser compress code, reduce file size
  • tslib: If lib is configured in tsconfig, you need to use tslib dependency
  • typescript: use TS syntax and type system

tool configuration

After installing and understanding rollup dependencies and plug-ins, we will configure the packaging tool

Create a new rollup.config.js configuration file in the root directory and enter the following code

import typescript from "@rollup/plugin-typescript";
import resolve from "@rollup/plugin-node-resolve";
import { readFileSync } from "fs";
import { terser } from "rollup-plugin-terser";
import alias from "@rollup/plugin-alias";
const packageJson = JSON.parse(readFileSync("./package.json", "utf8")); // 读取UMD全局模块名,在package中定义了
const pkgName = packageJson.umdModuleName;
export default {
  input: "src/index.ts",
  output: [
    {
      file: "dist/esm/index.js",
      format: "esm",
    },
    {
      file: "dist/cjs/index.js",
      format: "cjs",
    },
    {
      file: "dist/umd/index.js",
      format: "umd",
      name: pkgName,
      globals: {
        // 配置依赖中的UMD全局变量名
        "event-message-center": "MessageCenter",
        "task-queue-lib": "TaskQueue",
      },
    },
    {
      file: "dist/bundle/index.js",
      format: "iife",
      name: pkgName,
      plugins: [terser()],
    },
  ],
  plugins: [
    typescript({
      tsconfig: "./tsconfig.json",
    }),
    alias({
      resolve: [".js"],
    }),
    resolve(),
  ],
};

Create a new script command in the package

"rollup:build": "rm -fr dist && pnpm rollup -c"

Write code

Download two tools that depend on pnpm i event-message-center task-queue-lib

Export two downloaded tools event-message-center and task-queue-lib in index.ts

export * from "event-message-center"
export * from "task-queue-lib"
import eventMessageCenter from "event-message-center"
import taskQueueLib from "task-queue-lib"
export default {
    eventMessageCenter,
    taskQueueLib
}

Packaging & Publishing

Run pnpm run rollup:build to package the program

The files of the 4 module types are printed correctly

Finally, publish the code through npm publish

Amway has a wave of packaging tools I wrote before , and now the publish function has been added. Through the -pub command, you can directly git tag and publish to npm. Friends who are interested can try it

Summarize

This article takes TS+rollup as an example to introduce the whole process of installation, configuration, development and deployment of a toolkit. I hope it will be helpful to you.

Thank you for reading to the end, if you have any questions, please leave a message in the comment area or private message

If you like this article, please like and support the blogger, thank you

sample code

utils-lib-js - npm

utils-lib-js: JavaScript tool functions, some commonly used js functions encapsulated

Relevant information

Introduction | rollup.js Chinese documentation | rollup.js Chinese website

Guess you like

Origin blog.csdn.net/time_____/article/details/129846790