rollup/ tsup

86 阅读1分钟

rollup 打包工具类

  • package.json
{
  "name": "rollup-demo",
  "version": "1.0.0",
  "main": "index.js",
  "type": "module", // es6方式书写rollup.config.js
  "scripts": {
    "build": "rollup -c"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "rollup": "^4.44.1"
  },
  "devDependencies": {
    "@babel/core": "^7.27.7",
    "@babel/preset-env": "^7.27.2",
    "@rollup/plugin-babel": "^6.0.4",
    "@rollup/plugin-node-resolve": "^16.0.1",
    "@rollup/plugin-terser": "^0.4.4"  // 压缩代码
  }
}
  • rollup.config.js
import { babel } from "@rollup/plugin-babel";
import resolve from "@rollup/plugin-node-resolve";
import terser from "@rollup/plugin-terser";

export default {
  input: "src/index.js", // 打包入口文件
  output: {              // 打包产物
    file: "dist/utils.js",
    format: "esm", // esm || cjs || iife
  },
  plugins: [
    resolve(),
    babel({
      babelHelpers: "bundled",
      exclude: "node_modules/**",
      presets: [
        [
          "@babel/preset-env",
          {
            targets: "> 0.5%, ie >= 11", // 支持 IE11 及以上
          },
        ],
      ],
    }),
    terser(),
  ],
};

  • src目录编写工具类
// src/math.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;

// src/string.。
export const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);

// src/index.js
export * from './math';
export * from './string';
  • 注意 rollup 可配合babel等插件实现支持目标产物为es5.

tsup

  • package.json
{
  "name": "tsup-demo",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "tsup"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "devDependencies": {
    "tsup": "^8.5.0",
    "typescript": "^5.8.3"
  }
}
  • tsup.config.ts
import { defineConfig } from "tsup";

export default defineConfig({
    entry: ['src/index.ts'],
    format: ['esm', 'cjs'],
    dts: true,
    minify: true,
    sourcemap: true,
})
  • src目录编写工具类
// src/math.ts
export const add = (a: number, b: number) => a + b;
export const multiply = (a: number, b: number) => a * b;

// src/string.ts
export const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);

// src/index.ts
export * from './math';
export * from './string';
  • 注意 由于 ESBuild 天生不支持到 es5 的语法降级,所以在此 tsup 在此又选用了另一款编译框架来支持,那就是 SWC