登录
首页 >  文章 >  前端

Rollup打包JS库教程详解

时间:2025-11-04 11:20:34 421浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《Rollup打包JS库全攻略》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

使用 Rollup 打包 JavaScript 库,需安装 rollup 及插件如 @rollup/plugin-node-resolve、commonjs、typescript,配置 rollup.config.js 指定 input、output 多格式(esm/cjs)、external 依赖,结合 package.json 的 main/module/types/files 字段与 tsconfig.json 类型生成,执行 npm run build 构建并 npm publish 发布。

如何用Rollup打包一个库类型的JavaScript项目?

打包一个库类型的 JavaScript 项目,使用 Rollup 是一个非常高效且流行的选择,尤其适合构建用于发布到 npm 的库。Rollup 支持 Tree-shaking、模块化输出,并能生成多种格式的产物(如 ES Module、CommonJS、UMD 等)。以下是具体步骤和配置建议。

安装 Rollup 及必要插件

在项目根目录初始化 npm 并安装 Rollup:

npm init -y
npm install --save-dev rollup

根据你的项目需求,安装常用插件:

  • @rollup/plugin-node-resolve:让 Rollup 能加载 node_modules 中的第三方模块。
  • @rollup/plugin-commonjs:将 CommonJS 模块转换为 ES6 模块。
  • @rollup/plugin-typescript(可选):如果你使用 TypeScript。
  • tslib(可选):TypeScript 辅助函数库。
npm install --save-dev @rollup/plugin-node-resolve @rollup/plugin-commonjs
npm install --save-dev @rollup/plugin-typescript tslib

编写 rollup.config.js 配置文件

在项目根目录创建 rollup.config.js,以下是一个典型的库项目配置示例:

import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';

export default {
 input: 'src/index.ts', // 入口文件
 output: [
  {
   file: 'dist/bundle.esm.js',
   format: 'esm' // ES Module 格式
  },
  {
   file: 'dist/bundle.cjs.js',
   format: 'cjs' // CommonJS 格式
  }
 ],
 plugins: [
  resolve(),
  commonjs(),
  typescript({ tsconfig: './tsconfig.json' })
 ],
 external: ['lodash'] // 外部依赖,不打包进最终文件
};

说明:

  • input 指定库的入口文件,通常是 src/index.tsindex.js
  • output 数组支持多格式输出,推荐同时提供 ESM 和 CJS,以兼容不同环境。
  • external 列出你不想被打包的依赖,比如 React、Lodash 等,它们应由使用者提供。

配置 package.json 构建脚本与模块字段

package.json 中设置正确的字段,帮助工具识别你的库:

{
 "name": "your-awesome-lib",
 "version": "1.0.0",
 "main": "dist/bundle.cjs.js",
 "module": "dist/bundle.esm.js",
 "types": "dist/types/index.d.ts",
 "files": [
  "dist"
 ],
 "scripts": {
  "build": "rollup -c"
 }
}

关键字段解释:

  • main:Node.js 使用的 CommonJS 入口。
  • module:支持 Tree-shaking 的 ES Module 入口。
  • types:TypeScript 类型定义文件路径(需配合 tsc 生成)。
  • files:指定发布到 npm 的文件夹,避免上传无关内容。

如果你使用 TypeScript,确保 tsconfig.json 启用了类型生成:

{
 "compilerOptions": {
  "outDir": "dist",
  "declaration": true,
  "declarationDir": "dist/types"
 }
}

执行构建并发布

运行构建命令:

npm run build

构建成功后,会在 dist 目录生成对应文件。你可以本地测试:

npm pack

最后发布到 npm:

npm publish 基本上就这些。Rollup 能帮你产出干净、高效、兼容性好的库文件,特别适合组件库、工具函数库等场景。关键是配置好输入输出、外部依赖和模块规范。

今天关于《Rollup打包JS库教程详解》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>