技術(shù)棧
- react
- typescript
- sass
先置條件
- npm賬號
- 打包后的組件文件
- npm已經(jīng)綁定郵箱
先置知識
package.json
"name": "@3alan/ui", // 包名次员,@后跟的是組織名
"version": "0.2.10", // 包版本號,每次發(fā)版需要自行變更版本號
"private": false, // 是否為私有包
"main": "dist/index.cjs.js", // 包入口文件
"module": "dist/index.esm.js",
"types": "dist/types/index.d.ts", // typescript聲明文件
"license": "MIT", // 開源協(xié)議
"description": "hand drawn react components", // 包描述
"author": "3Alan", // 作者
"homepage": "https://alan-ui.vercel.app/", // 網(wǎng)站
"repository": {
"type": "git",
"url": "https://github.com/3Alan/alan-ui"
},
"files": [
"dist"
], // 需要上傳到npm上的文件
"keywords": [
"react",
"components",
"ui",
"hand drawn"
], // 關(guān)鍵字:用來描述你的包
"dependencies": {
},
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
}, // 宿主(即需要使用改包的項目)需要具備的依賴
上圖更直觀了解
image-20210910105028280
打包組件庫
使用rollup打包
先置條件
yarn add rollup -D
- 插件根據(jù)自己需求安裝
在根目錄下創(chuàng)建rollup.config.js
文件
文件中使用的插件自行安裝
import typescript from '@rollup/plugin-typescript';
// 用來處理import 'xxx.scss'問題
import postcss from 'rollup-plugin-postcss';
// 壓縮代碼
import { terser } from 'rollup-plugin-terser';
// 類似webpack-bundle-analyzer
import { visualizer } from 'rollup-plugin-visualizer';
// 拷貝靜態(tài)資源
import copy from 'rollup-plugin-copy';
// 將package.json中的依賴打包
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import pkg from './package.json';
const copyRight = `/*!
Copyright (c) 2021 3Alan.
Licensed under the MIT License (MIT)
*/`;
// eslint-disable-next-line import/no-anonymous-default-export
export default {
input: './src/index.ts',
output: [
{
file: pkg.main,
format: 'cjs',
footer: copyRight
},
{
file: pkg.module,
format: 'esm',
footer: copyRight
}
],
plugins: [
// roughjs將會被一同打包進dist中
resolve({ resolveOnly: ['roughjs'] }),
commonjs(),
// 將ts轉(zhuǎn)化成es5語法并生成類型文件
typescript({
tsconfig: './tsconfig.build.json',
// 生成d.ts文件以及生成路徑
declaration: true,
declarationDir: 'types'
}),
copy({
targets: [{ src: 'src/components/style/*.ttf', dest: 'dist' }]
}),
postcss(),
terser(),
visualizer()
]
};
打包腳本
安裝刪除工具(用來每次打包前清除dist目錄)
yarn add rimraf -D
"build:sass": "sass ./src/components/style/index.scss ./dist/index.css
"clean": "rimraf ./dist",
"build": "yarn clean && rollup -c && yarn build:sass",
打包后的目錄:
dist
├── index.cjs.js
├── index.css
├── index.css.map
├── index.esm.js
├── Stanberry.ttf
└── types
發(fā)布npm
先置條件
npm已登錄
npm鏡像源沒有切換過脉漏,可以使用
npm whoami
驗證,如果能正確返回npm用戶名即可package.json
中version
高于上次發(fā)布的版本號
發(fā)布腳本
npm publish
-
可在package.json中配置鉤子發(fā)布前自動打包
"prepublishOnly": "yarn build",