如何在基于Rollup的NPM发布型设计系统中集成Ant Design或Chakra UI?
设计系统集成AntD/Chakra UI并通过Rollup构建发布的解决方案
核心思路
设计系统作为NPM类库,不需要自身完成UI框架的全局初始化(比如AntD的ConfigProvider、Chakra的ChakraProvider),这些配置应该交给使用你的设计系统的业务项目去做。你的核心工作是按需引入UI组件、正确配置依赖关系、调整Rollup构建规则,避免把整个UI库打包进你的设计系统。
针对Ant Design的配置步骤
配置依赖关系
在package.json中添加peerDependencies,明确告知用户项目需要自行安装的依赖:"peerDependencies": { "antd": "^5.x", "react": "^18.x", "react-dom": "^18.x" }, "devDependencies": { "antd": "^5.x" // 仅开发环境安装用于调试 }组件中按需引入
不要在设计系统代码中全局引入AntD,而是在单个组件中按需导入所需组件:// 示例组件 import { Button } from 'antd'; import React from 'react'; export const WbsButton = (props) => { return <Button {...props} />; };Rollup排除外部依赖
在rollup.config.js中添加external选项,避免把AntD、React等依赖打包进你的库:export default { input: 'src/index.js', // 若没有入口文件可新建,导出所有组件 external: ['react', 'react-dom', 'antd'], // 其他配置... };
针对Chakra UI的配置步骤
配置依赖关系
同样在package.json中添加peerDependencies:"peerDependencies": { "@chakra-ui/react": "^2.x", "@emotion/react": "^11.x", "@emotion/styled": "^11.x", "framer-motion": "^10.x", "react": "^18.x", "react-dom": "^18.x" }, "devDependencies": { "@chakra-ui/react": "^2.x", "@emotion/react": "^11.x", "@emotion/styled": "^11.x", "framer-motion": "^10.x" }组件开发规范
直接使用Chakra的组件进行封装,无需在设计系统中初始化ChakraProvider:import { Button } from '@chakra-ui/react'; import React from 'react'; export const WbsChakraButton = (props) => { return <Button variant="solid" {...props} />; };Rollup排除外部依赖
更新rollup.config.js的external选项:external: ['react', 'react-dom', '@chakra-ui/react', '@emotion/react', '@emotion/styled', 'framer-motion']
Rollup构建关键调整
添加必要插件
确保你的Rollup配置包含以下插件(需先安装到devDependencies):@rollup/plugin-node-resolve:解析第三方模块@rollup/plugin-babel:处理JSX和ES6+语法(需配置React preset)rollup-plugin-postcss:处理组件样式(如果你的设计系统有自定义CSS)
示例插件配置:
import resolve from '@rollup/plugin-node-resolve'; import babel from '@rollup/plugin-babel'; import postcss from 'rollup-plugin-postcss'; 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 } ], external: [...], // 前面配置的外部依赖 plugins: [ resolve(), babel({ presets: ['@babel/preset-react'], exclude: 'node_modules/**' }), postcss({ extract: true, // 提取CSS到单独文件 modules: false }) ] };设置package.json入口
在package.json中指定构建产物的入口:"main": "dist/index.cjs.js", "module": "dist/index.esm.js", "types": "dist/index.d.ts" // 如果用TypeScript开发,需添加类型文件入口
学习资源建议
- Rollup官方文档:重点学习「库打包」章节,掌握
external、peerDependencies的用法 - Ant Design 官方文档:查看「组件库开发」相关内容,了解按需加载和依赖配置规范
- Chakra UI 官方文档:学习基于Chakra封装组件的最佳实践
- NPM官方文档:深入理解
peerDependencies的作用,避免依赖冲突
内容的提问来源于stack exchange,提问作者LayTexas
相关产品推荐
相关产品推荐

