前言
项目中会用到工具库、函数库以及一些跟框架绑定的组件,如果这些基础模块每个项目都实现一套,维护起来那真的头大,你说呢😉
搭建流程
准备工作
创建文件夹myLib、安装Git以及pnpm
目录大概就系这样子:
myLib
├── .husky
│ ├── commit-msg
│ └── pre-commit
├── packages
│ └── utils
│ ├── lib
│ │ ├── index.cjs.js
│ │ ├── index.esm.js
│ │ └── index.d.ts
│ ├── src
│ │ └── index.ts
│ ├── rollup.config.js
│ ├── tsconfig.json
│ └── package.json
├── .eslintrc.js
├── .prettierrc
├── commitlint.config.js
├── pnpm-workspace.yaml
├── tsconfig.json
└── package.json
配置Typescript
pnpm add -D -w typescript tslib
pnpm tsc --init
tsconfig.json
{
"files": [],
"references": [
{ "path": "./packages/utils" }
]
}
pnpm-workspace.yaml
packages:
- 'packages/*'
package.json
"scripts": {
"postinstall": "husky install",
"lint": "eslint packages/**/*.{ts,js} --fix"
}
子包
tsconfig.json配置
{
"compilerOptions": {
"rootDir": "./src",
"declaration": true,
"declarationDir": "./lib",
"emitDeclarationOnly": true,
"module": "esnext",
"target": "es6",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*"]
}
Rollup打包
pnpm add -D rollup @rollup/plugin-node-resolve @rollup/plugin-commonjs @rollup/plugin-typescript typescript
rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';export default {
input: "src/index.ts",
output: [
{
file:"lib/index.cjs.js",
format:"cjs",
},
{
file:"lib/index.esm.js",
format:"esm",
},
],
plugins:[
resolve(),
commonjs(),
typescript()
]
};
package.json
"scripts": {
"build": "rollup -c"
}
git commit 验证
记得用git先初始化下仓库
pnpm add -D -w husky @commitlint/{config-conventional,cli}
pnpm husky installpnpm dlx husky-init --pm=pnpm
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional']
};
配置Eslint和Prettier
pnpm add -D -w eslint prettier eslint-config-prettier eslint-plugin-prettier
eslint.config.js
const path = require('path');
const { ESLint } = require('eslint');
const tsParser = require('@typescript-eslint/parser');
const tsPlugin = require('@typescript-eslint/eslint-plugin');
const prettierPlugin = require('eslint-plugin-prettier');module.exports = [
{
files: ['packages/**/src/**/*.{ts,js}'],
ignores: ['node_modules'],
languageOptions: {
parser: tsParser,
parserOptions: {
ecmaVersion: 2020
},
},
plugins: {
'@typescript-eslint': tsPlugin,
prettier: prettierPlugin,
},
rules: {
'prettier/prettier': 'error',
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'warn',
},
},
]
.prettierrc
{
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80
}
.husky/pre-commit
pnpm run lint
打包
最后
整体的框框已经搭建起来,把需要的工具、函数和组件写入即可,发布子包到私有仓库即可内部使用啦~