听说vite已经到了2.x版本,赶紧打开文档看了看
嗯~ o( ̄▽ ̄)o,库模式?必须试试
yarn create vite
输入项目名称后,选择react回车、再选中react回车,ok,生成的目录结构如下
打开vite.config.js,默认配置如下:
import { defineConfig } from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [reactRefresh()]
})
那么我们按照库模式修改配置,打包文件输出到lib/dist目录下
import { defineConfig } from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'
import { resolve } from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [reactRefresh()],
build: {
lib: {
entry: resolve(__dirname, 'components/index.jsx'),
name: 'callduck-design',
// formats: ['es'],
fileName: (format) => `callduck-design.${format}.js`
},
rollupOptions: {
// 确保外部化处理那些你不想打包进库的依赖
external: ['react'],
output: {
// 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
globals: {
react: 'React'
}
}
},
outDir: 'lib/dist'
}
})
库入口是components目录下的index.jsx文件,该文件用于导出库组件,如:
export { default as Button } from './button/button'
那么我们需要写个button组件
import React from 'react'
function Button({children}) {
return (
<button>{children}</button>
)
}
export default Button
接下来就可以打包组件了,
yarn
yarn build
结果如下图:
打包后生成了两个文件
因为vite默认是生成es和umd两种类型的,如果只需要一种,可以修改配置文件中build.lib.formats选项。
文件打包好,我们需要发布到npm上,首先我们在本机登录一下npm账号
yarn login
出现下图显示表示登录成功。什么,还没npm账号?作为新时代农民工,npm账号必须注册一下(此处省略)
我们要发布的包在lib目录下,那么在该目录下添加package.json文件
"name": "callduck-design",
"version": "0.0.1",
"description": "An enterprise-class UI design language and React components implementation",
"keywords": [
"callduck",
"component",
"components",
"design",
"framework",
"frontend",
"react",
"react-component",
"ui"
],
"files": ["dist"],
"main": "./dist/callduck-design.umd.js",
"module": "./dist/callduck-design.es.js",
"exports": {
".": {
"import": "./dist/callduck-design.es.js",
"require": "./dist/callduck-design.umd.js"
}
},
"repository": "https://github.com/YutLee/callduck-design.git",
"author": "YutLee",
"license": "MIT"
}
那么我们进入到该目录
cd lib
激动人心的时刻到了,输入发布命令
yarn publish
结果... ...
什么,竟然报错了,好吧,原来是镜像搞的鬼
切换回原镜像
OK,重新yarn publish
打开浏览器,进入https://www.npmjs.com/,登录账号,进入到packages查看是否上传成功
QQ截图20210826155829.png
发布后,我们就可以使用这个包了,就在刚才的项目里引用试试
yarn add callduck-design
到src/app.jsx文件里引用这个组件
import React from 'react'
import './app.css'
import { Button } from 'callduck-design'
function App() {
return (
<Button>CallDuck Design</Button>
)
}
export default App
回到命令行,启动项目
yarn dev