使用 Storybook 和 Vite 建立 React 元件庫

建立專案

建立專案。

1
2
mkdir react-storybook
cd react-storybook

初始化專案。

1
npm init

新增 .gitignore 檔。

1
2
/node_modules
/dist

安裝依賴套件

安裝 Vite 工具。

1
npm i vite -D

安裝 React 框架。

1
npm i react@17.0.0 react-dom@17.0.0 -D

安裝 Storybook 工具。

1
npx sb@latest init

啟動介面

啟動 Storybook 介面。

1
npm run storybook

編譯

新增 index.ts 檔,將元件匯出。

1
2
3
4
5
6
7
8
9
10
import Button from "./components/Button";

const components = {
Button,
};

export {
components as default,
Button,
};

更新 package.json 檔。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
{
"name": "@memochou1993/react-storybook",
"version": "0.1.0",
"description": "",
"main": "./dist/index.cjs.js",
"module": "./dist/index.es.js",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"repository": "",
"scripts": {
"build": "vite build",
"test": "echo \"Error: no test specified\" && exit 1",
"storybook": "start-storybook -p 6006",
"build-storybook": "build-storybook",
"lint": "eslint src --ext .jsx,.js,.tsx,.ts"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^17.0.0",
"react-dom": "^17.0.0",
"styled-components": "^5.3.5"
},
"devDependencies": {
"@storybook/addon-actions": "^6.4.22",
"@storybook/addon-essentials": "^6.4.22",
"@storybook/addon-interactions": "^6.4.22",
"@storybook/addon-links": "^6.4.22",
"@storybook/react": "^6.4.22",
"@storybook/testing-library": "^0.0.11",
"@types/styled-components": "^5.1.25",
"@typescript-eslint/eslint-plugin": "^5.21.0",
"@vitejs/plugin-react": "^1.3.2",
"eslint-plugin-react": "^7.29.4",
"vite": "^2.9.5",
"vite-plugin-dts": "^1.1.1",
"vue-tsc": "^0.34.11"
},
"exports": {
".": {
"import": "./dist/index.es.js",
"require": "./dist/index.cjs.js"
}
}
}

新增 vite.config.ts 檔:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import react from '@vitejs/plugin-react';
import path from 'node:path';
import { defineConfig } from 'vite';
import dts from 'vite-plugin-dts';

export default defineConfig({
plugins: [
react(),
dts({
insertTypesEntry: true,
}),
],
build: {
lib: {
entry: path.resolve(__dirname, 'src/index.ts'),
name: 'Web3',
formats: ['es', 'cjs'],
fileName: (format) => `index.${format}.js`,
},
rollupOptions: {
external: ['react', 'react-dom', 'styled-components'],
output: {
exports: "named",
globals: {
react: 'React',
'react-dom': 'ReactDOM',
'styled-components': 'styled',
},
},
},
},
});

修改 tsconfig.json 檔。

1
2
3
{
"isolatedModules": true,
}

執行編譯。

1
npm run build

發布

修改 package.json 檔,注意套件名稱必須是獨一無二的。

1
2
3
4
{
"name": "@memochou1993/react-storybook",
"repository": "https://github.com/memochou1993/react-storybook.git"
}

提交修改。

1
2
git add .
git commit -m "Initial commit"

新增版本。

1
npm version 0.1.0 -m "First release"

登入 npm。

1
npm login

發布套件。

1
npm publish --access=public

程式碼

參考資料