You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Rollup打包React组件库并分离组件与CSS及主项目消费方案

Rollup实现React组件库与CSS分离打包及消费指南

一、Rollup配置实现组件与CSS分离

1. 安装必要插件

首先安装处理CSS的Rollup插件及PostCSS工具链:

npm install rollup-plugin-postcss postcss cssnano autoprefixer --save-dev

2. 修改Rollup配置文件

在rollup.config.js中引入并配置rollup-plugin-postcss,核心通过extract选项将CSS抽离为独立文件:

import postcss from 'rollup-plugin-postcss';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
import { babel } from '@rollup/plugin-babel';

export default {
  input: 'src/index.js', // 组件库入口文件
  output: [
    {
      file: 'dist/index.esm.js',
      format: 'esm',
      sourcemap: true
    },
    {
      file: 'dist/index.cjs.js',
      format: 'cjs',
      sourcemap: true
    }
  ],
  plugins: [
    babel({
      presets: ['@babel/preset-react'],
      exclude: 'node_modules/**',
      babelHelpers: 'bundled'
    }),
    postcss({
      extract: 'dist/default-theme.css', // 指定输出的默认主题CSS文件名
      plugins: [
        autoprefixer(), // 自动添加浏览器前缀
        cssnano() // 生产环境压缩CSS(可选)
      ],
      sourceMap: true
    })
  ],
  external: ['react', 'react-dom'] // 排除React依赖,由宿主项目提供
};

3. 配置package.json

确保发布时包含打包后的JS和CSS文件,同时正确声明入口与依赖:

{
  "name": "your-component-lib",
  "version": "1.0.0",
  "main": "dist/index.cjs.js",
  "module": "dist/index.esm.js",
  "files": [
    "dist/**/*"
  ],
  "peerDependencies": {
    "react": "^16.8.0 || ^17.0.0 || ^18.0.0",
    "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0"
  }
}

二、主项目消费组件库

1. 全局引入(推荐)

安装组件库后,在主项目入口文件中一次性导入默认主题CSS和组件:

// src/index.js
import 'your-component-lib/dist/default-theme.css';
import { Button, Card } from 'your-component-lib';

function App() {
  return (
    <div>
      <Button>Click Me</Button>
      <Card>Card Content</Card>
    </div>
  );
}

2. 按需引入(体积优化)

若组件库按单个组件拆分打包(需调整Rollup为多入口配置),可单独引入目标组件及对应样式:

import Button from 'your-component-lib/dist/Button';
import 'your-component-lib/dist/Button.css';

function Demo() {
  return <Button>Isolated Button</Button>;
}

常见注意事项

  • 主项目需提前安装React和ReactDOM,避免因peerDependencies缺失导致报错。
  • 若组件库使用CSS Modules,需在postcss配置中添加modules: true,并在组件中按模块方式导入样式。
  • 开发组件库时,可配合Storybook预览组件,直接在Storybook配置中引入CSS文件即可实时查看样式效果。

内容的提问来源于stack exchange,提问作者Dmitry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 22:01:37