前言
文章首发于本人个人网站:星空海绵
下面涉及到的项目demo github 地址:
1.搭建项目
- 1.dumi介绍:dumi,中文发音嘟米,是一款由阿里开源的为组件开发场景而生的静态站点框架,antd组件库也是用dumi搭建的,与 father 一起为开发者提供一站式的组件开发体验,father 负责组件源码构建,而 dumi 负责组件开发及组件文档生成。
- 2.项目初始化
npx create-dumi
上面依赖安装工具我选择的是pnpm,然后启动命令就是:
pnpm start
启动起来浏览器访问就可以看见了:
然后点击上面页面中的Foo就可以看见一个与antd文档上一样的一个组件了:
到这使用dumi搭建一个组件库初始化的部分就完成了,然后就是将你的组件库发布到npm上,别人可以当依赖使用。
2.npm发布组件库
-
1.首先注册一个npm账号,这个自己去注册就行,npm官网
-
2.修改项目中的package.json,将private字段设置为false,表示非私有包,我的package.json如下,仅供参考:
{
"name": "sparx-ui",
"version": "1.0.0",
"description": "A react library developed with dumi",
"private": false,
"module": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"start": "npm run dev",
"dev": "dumi dev",
"build": "father build",
"build:watch": "father dev",
"docs:build": "dumi build",
"prepare": "husky install && dumi setup",
"doctor": "father doctor",
"lint": "npm run lint:es && npm run lint:css",
"lint:css": "stylelint \"{src,test}/**/*.{css,less}\"",
"lint:es": "eslint \"{src,test}/**/*.{js,jsx,ts,tsx}\"",
"prepublishOnly": "father doctor && npm run build"
},
"authors": [
"imxkhm@gmail.com"
],
"license": "MIT",
"keywords": ["React","dumi","sparx-ui","sparx","ui"],
"homepage": "https://github.com/yukiyukixing/sparx-ui",
"repository": {
"type": "git",
"url": "https://github.com/yukiyukixing/sparx-ui.git"
},
"files": [
"dist"
],
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
},
"lint-staged": {
"*.{md,json}": [
"prettier --write --no-error-on-unmatched-pattern"
],
"*.{css,less}": [
"stylelint --fix",
"prettier --write"
],
"*.{js,jsx}": [
"eslint --fix",
"prettier --write"
],
"*.{ts,tsx}": [
"eslint --fix",
"prettier --parser=typescript --write"
]
},
"publishConfig": {
"access": "public"
},
"peerDependencies": {
"react": ">=16.9.0",
"react-dom": ">=16.9.0"
},
"devDependencies": {
"@commitlint/cli": "^17.6.5",
"@commitlint/config-conventional": "^17.6.5",
"@types/react": "^18.2.12",
"@types/react-dom": "^18.2.5",
"@umijs/lint": "^4.0.71",
"dumi": "^2.2.1",
"eslint": "^8.43.0",
"father": "^4.2.3",
"husky": "^8.0.3",
"lint-staged": "^13.2.2",
"prettier": "^2.8.8",
"prettier-plugin-organize-imports": "^3.2.2",
"prettier-plugin-packagejson": "^2.4.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"stylelint": "^15.8.0"
}
}
- 3.npm发布
执行登录npm命令:
npm login
然后执行npm publish命令进行发布:
npm publish
发布成功就能在你的npm上看见这个包了
3.在一个React项目中使用你刚发布的包
- 1.创建一个React项目
这里你可以使用React官方脚手架创建,也可以不使用React脚手架创建一个React项目
- 2.在你的项目中使用你刚发布的npm包
首先,安装你刚发布的包的依赖
npm i sparx-ui
使用刚才发布包里面的组件:
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Foo } from 'sparx-ui';
function App() {
return (
<div>
<Foo title="Hello dumi!" />
</div>
);
}
const root = document.getElementById('root');
createRoot(root).render(<App />);
启动你的项目可以看到:
然后你在搭建组件库的过程中还会遇到一些组件库相关的构建配置啊,组件库需要的功能相关的问题啊,后续我还会出一篇我们搭建组件库遇到的实践的相关的文章,完结,撒花!