开场
咱们今天接着上一篇的
组件库搭建
开发。本篇主要做的是js、css、vue组件、ts类的声明
的打包配置 采用gulp来控制打包流程,采用rollup打包、借鉴elementPlus官网
执行命令全局安装gulp
脚手架
pnpm install --global gulp-cli复制代码
在根目录下安装 gulp @types/gulp sucrase
pnpm install gulp @types/gulp sucrase -w -D复制代码
在根目录新建 build
文件夹
mkdir build复制代码
在build
中新建gulpfile.ts
文件 新增utils
文件夹
touch gulpfile.tsmkdir utils复制代码
gulpfile.ts
代码如下:
// 打包方式:串行(series) 并行(parallel)import { series, parallel } from "gulp";import { withTaskName,runTask } from "./utils"/** * 1. 打包样式 * 2. 打包工具方法 * 3. 打包所有组件 * 4. 打包每个组件 * 5. 生成一个组件库 * 6. 发布组件 */export default series( withTaskName("clean", async () => runTask('rm -rf ./dist')), // 删除dist目录);复制代码
在utils/index.ts
中实现 withTaskName runTask
方法
/** * 子进程 * child_process.spawn(command[, args][, options]) * command <string> 要运行的命令。 * args <string[]> 字符串参数列表。 * options <Object> * - cwd <string> | <URL> 子进程的当前工作目录 * - stdio <Array> | <string> 子进程的标准输入输出配置。'inherit':通过相应的标准输入输出流传入/传出父进程 * - shell <boolean> | <string> 如果是 true,则在 shell 内运行 command。 在 Unix 上使用 '/bin/sh',在 Windows 上使用 process.env.ComSpec。 可以将不同的 shell 指定为字符串。 请参阅 shell 的要求和默认的 Windows shell。 默认值: false (没有 shell)x */import { spawn } from 'child_process'import type { TaskFunction } from 'gulp'import {projRoot,buildRoot} from './paths'// 自定义每个task的nameexport const withTaskName = <T extends TaskFunction>(name: string, fn: T) => Object.assign(fn, { displayName: name }) // 在node中开启一个子进程来运行脚本 const run = async (command: string, cwd: string = projRoot) => new Promise<void>((resolve, reject) => { const [cmd, ...args] = command.split(' ') const app = spawn(cmd, args, { cwd, stdio: 'inherit', shell: true, }) const onProcessExit = () => app.kill('SIGHUP') app.on('close', (code) => { process.removeListener('exit', onProcessExit) if (code === 0) resolve() else reject( new Error(`Command failed. \n Command: ${command} \n Code: ${code}`) ) }) process.on('exit', onProcessExit) })// 执行方法 export const runTask = (name: string) => withTaskName(`shellTask:${name}`, () => run(`pnpm run start ${name}`, buildRoot) )复制代码
在utils/paths.ts
中实现 定义 根目录 打包目录
import { resolve } from 'path'// 根目录export const projRoot = resolve(__dirname, '..','..')export const buildRoot = resolve(projRoot, 'internal', 'build')/** `/dist` */export const buildOutput = resolve(projRoot, 'dist')复制代码
在根目录下的package.json
中增加build
脚本:gulp -f build/gulpfile.ts
,指定配置文件为build目录下的gulpfile.ts
文件:
"scripts": { "dev": "pnpm -C play dev", + "build": "gulp -f build/gulpfile.ts" },复制代码
接下来测试一下,在根目录新建一个dist
目录,执行pnpm build
,看看有没有删除掉
gulp处理scss
在theme-chalk
下增加gulp
配置文件gulpfile.ts
在package.json
下,增加build
脚本
"scripts": { "build": "gulp" }复制代码
安装相关依赖在根目录
# 安装相关依赖pnpm install gulp-sass @types/gulp-sass @types/sass gulp-autoprefixer @types/gulp-autoprefixer @types/gulp-clean-css gulp-clean-css -w -D复制代码
包名作用gulp-sass将scss编译为css@types/gulp-sassgulp-sass 的TS类声明@types/sasssass的 TS类声明gulp-autoprefixer自动添加前缀@types/gulp-autoprefixergulp-autoprefixer 的TS类声明gulp-clean-css压缩css文件@types/gulp-clean-cssgulp-clean-css 的TS声明//gulpfile.tsimport gulpSass from "gulp-sass";import dartSass from "sass";import autoprefixer from "gulp-autoprefixer";import cleanCss from "gulp-clean-css";import path from "path";/** * gulp是类似一个管道的方式执行,从入口开始到出口,中间一步步执行 */import { series, src, dest } from "gulp";/** * 对sass文件做处理 */function compile() { const sass = gulpSass(dartSass); return src(path.resolve(__dirname, "./src/*.scss")) .pipe(sass.sync())//转译 .pipe(autoprefixer())//添加前缀 .pipe(cleanCss())//压缩 .pipe(dest("./dist/css"));//将处理完的生成在dist目录}/*** 把打包好的css输出到根目录的dist*/function copyfullstyle(){ const rootDistPath = path.resolve(__dirname,'../../dist/theme-chalk') return src(path.resolve(__dirname,'./dist/**')).pipe(dest(rootDistPath))}export default series(compile,copyfullstyle);复制代码
在打包入口文件中加入执行命令
export default series( withTaskName("clean", () => run('rm -rf ./dist')), // 删除dist目录 //新增的命令 找到带有@xlz-ui/*包的所有build命令 parallel( withTaskName("buildPackages", () => run("pnpm run --filter @xlz-ui/* --parallel build") ), ));复制代码
执行打包命令pnpm build
gulp处理utils工具包
在utils
下增加gulp
配置文件gulpfile.ts
,并且安装依赖gulp-typescript
来处理ts文件
# 安装依赖pnpm install gulp-typescript -w -D复制代码
//gulpfile.tsimport { buildPackages } from "../../build/packages"export default buildPackages(__dirname,'utils')复制代码
在build
下新增packages.ts utils/config.ts
文件
touch packages.tstouch config.ts复制代码
将ts
分别打包为cjs
和esm
两种模块规范 在config.ts
配置如下:
import path from "path";import { outDir } from "./paths";export const buildConfig = { esm: { module: "ESNext", // tsconfig输出的结果es6模块 format: "esm", // 需要配置格式化化后的模块规范 output: { name: "es", // 打包到dist目录下的那个目录 path: path.resolve(outDir, "es"), }, bundle: { path: "xlz-plus/es", }, }, cjs: { module: "CommonJS", format: "cjs", output: { name: "lib", path: path.resolve(outDir, "lib"), }, bundle: { path: "xlz-plus/lib", }, },};export type BuildConfig = typeof buildConfig;复制代码
packages.ts
配置
import { series, parallel, src, dest } from "gulp";import { buildConfig } from "./utils/config";import path from "path";import { outDir, projectRoot } from "./utils/paths";import ts from "gulp-typescript";import { withTaskName } from "./utils";// 打包处理export const buildPackages = (dirname: string, name: string) => { const tasks = Object.entries(buildConfig).map(([module, config]) => { const output = path.resolve(dirname, config.output.name); // 安装依赖gulp-typescript return series( // 处理ts文件 withTaskName(`build${dirname}`, () => { const tsConfig = path.resolve(projectRoot, "tsconfig.json"); // ts配置文件路径 const inputs = ["**/*.ts", "!gulpfile.ts", "!node_modules"]; return src(inputs) .pipe( ts.createProject(tsConfig, { declaration: true, // 需要生成声明文件 strict: false, // 关闭严格模式 module: config.module, })() ) .pipe(dest(output)); }), withTaskName(`copy:${dirname}`,() => { // 将打包好的文件放到 es=>utils 和 lib => utils // 将utils模块拷贝到dist目录下的es和lib目录 return src(`${output}/**`).pipe(dest(path.resolve(outDir,config.output.name,name))) }) ); }); return parallel(...tasks);};复制代码
执行打包pnpm build
发现dist
下有 es lib
两个文件夹
gulp+rollup打包vue组件
首先安装依赖包
pnpm install rollup @rollup/plugin-node-resolve @rollup/plugin-commonjs rollup-plugin-typescript2 rollup-plugin-vue rollup-plugin-cleanup rollup-plugin-postcss rollup-plugin-terser @vue/compiler-sfc -D -w复制代码
在packages中新增一个文件夹xlz-ui
打包组件的文件 初始化执行pnpm init
配置如下:
{ "name": "xlz-ui", "version": "1.0.0", "description": "", "main": "lib/index.js", "module": "es/index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "xlz-ui" ], "author": "", "license": "ISC"}复制代码
在新增一个index.ts
文件 处理按需加载与批量导入
import * as components from '@xlz-ui/components'export * from "@xlz-ui/components";import type { App } from "vue"; // ts中的优化只获取类型export default { install: (app: App) => { for (const comkey in components) { app.component((components as any)[comkey].name, (components as any)[comkey]) } }}复制代码
开始配置打包 在build/utils/
下index.ts
与paths.ts
新增内容
//index.ts下新增 // 重写打包后的@xlz-ui 路径 export const pathRewriter = (format) => { return (id: any) => { id = id.replaceAll("@xlz-ui", `xlz-ui/${format}`); return id; }; };复制代码
//paths.ts新增// xlz-ui 入口 index.tsexport const xlzRoot = resolve(projRoot,'/packages/xlz-ui')// 组件目录export const compRoot = resolve(projRoot,'packages/components')复制代码
build下新增full-component.ts
做编译
import { nodeResolve } from "@rollup/plugin-node-resolve"; // 处理文件路径 import commonjs from "@rollup/plugin-commonjs"; // 将 CommonJS 模块转换为 ES6 import vue from "rollup-plugin-vue"; import RollupPluginPostcss from 'rollup-plugin-postcss'; // 解决组件内部如果有css 打包会报错的css插件 import typescript from "rollup-plugin-typescript2"; import { parallel } from "gulp"; import Autoprefixer from 'autoprefixer'import cssnano from 'cssnano' import path from "path"; import { outDir, xlzRoot } from "./utils/paths"; import { rollup, OutputOptions } from "rollup"; import fs from "fs/promises"; import { terser } from 'rollup-plugin-terser';// 压缩js代码 import cleanup from 'rollup-plugin-cleanup';// 去除无效代码 import { buildConfig } from "./utils/config"; import { pathRewriter } from "./utils"; const buildFull = async () => { // rollup 打包的配置信息 const config = { input: path.resolve(xlzRoot, "index.ts"), // 打包入口 plugins: [ nodeResolve(), vue({ preprocessStyles: false }), typescript(), RollupPluginPostcss({ extract: 'theme-chalk/components-style.css' , plugins: [Autoprefixer(),cssnano()] }), commonjs(), cleanup(), terser({ compress: { drop_console: true }})// 压缩js代码 及删除console ], external: (id) => /^vue/.test(id), // 打包的时候不打包vue代码 }; // 组件库两种使用方式 import 导入组件库 在浏览器中使用script // esm umd const buildConfig = [ { format: "umd", // 打包的格式 file: path.resolve(outDir, "index.js"), name: "xlz-plus", // 全局变量名字 exports: "named", // 导出的名字 用命名的方式导出 libaryTarget:"" name:"" globals: { // 表示使用的vue是全局的 vue: "Vue", }, }, { format: "esm", file: path.resolve(outDir, "index.esm.js"), }, ]; let bundle = await rollup(config); return Promise.all( buildConfig.map((option) => { bundle.write(option as OutputOptions); }) ); }; async function buildEntry() { // 读取xlz-ui目录下的所有内容,包括目录和文件 const entryFiles = await fs.readdir(xlzRoot, { withFileTypes: true }); // 过滤掉 不是文件的内容和package.json文件 index.ts 作为打包入口 const entryPoints = entryFiles .filter((f) => f.isFile()) .filter((f) => !["package.json"].includes(f.name)) .map((f) => path.resolve(xlzRoot, f.name)); const config = { input: entryPoints, plugins: [ nodeResolve(), vue(), typescript(), cleanup(), terser({ compress: { drop_console: true }})// 压缩js代码 及删除console ], external: (id: string) => /^vue/.test(id) || /^@xlz-ui/.test(id), }; const bundle = await rollup(config); return Promise.all( Object.values(buildConfig) .map((config) => ({ format: config.format, dir: config.output.path, paths: pathRewriter(config.output.name), })) .map((option) => bundle.write(option as OutputOptions)) ); } // gulp适合流程控制和代码的转义 没有打包的功能 export const buildFullComponent = parallel(buildFull, buildEntry);复制代码
修改build/gulpfile.ts
文件
// 打包方式:串行(series) 并行(parallel)import { series, parallel } from "gulp";import { withTaskName,run } from "./utils"/** * 1. 打包样式 * 2. 打包工具方法 * 3. 打包所有组件 * 4. 打包每个组件 * 5. 生成一个组件库 * 6. 发布组件 */export default series( withTaskName("clean", () => run('rm -rf ./dist')), // 删除dist目录 parallel( withTaskName("buildPackages", () => run("pnpm run -C packages/utils build") // run("pnpm run --filter ./packages --parallel build") 在我本地有点问题就换了个写法 有兴趣的可以自己在本地试一试 ), withTaskName("buildComponent", () => run("pnpm run -C packages/theme-chalk build")), withTaskName("buildFullComponent", () => run("pnpm run build buildFullComponent") ), ));// 任务执行器 gulp 任务名 就会执行对应的任务export * from "./full-component";//新增的自定义任务复制代码
可以执行pnpm build
看看有没有问题 没有问题继续操作怎么把编译后的文件copy
到dist
目录
在新增文件build/component.ts
安装依赖包
pnpm install fast-glob ts-morph -w -D复制代码
/** * 安装依赖 pnpm install fast-glob ts-morph -w -D */ import { nodeResolve } from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; import vue from "rollup-plugin-vue"; import typescript from "rollup-plugin-typescript2"; import RollupPluginPostcss from 'rollup-plugin-postcss'; // 解决组件内部如果有css 打包会报错的css插件 import Autoprefixer from 'autoprefixer'import cssnano from 'cssnano' import { series, parallel } from "gulp"; import { sync } from "fast-glob"; // 同步查找文件 import { compRoot, outDir, projRoot } from "./utils/paths"; import path from "path"; import { rollup, OutputOptions } from "rollup"; import { buildConfig } from "./utils/config"; import { pathRewriter, run } from "./utils"; import { Project, SourceFile } from "ts-morph"; import { terser } from 'rollup-plugin-terser';// 压缩js代码import cleanup from 'rollup-plugin-cleanup';// 去除无效代码 import glob from "fast-glob"; import * as VueCompiler from "@vue/compiler-sfc"; import fs from "fs/promises"; const buildEachComponent = async () => { // 打包每个组件 // 查找components下所有的组件目录 ["icon"] const files = sync("*", { cwd: compRoot, onlyDirectories: true, // 只查找文件夹 }); // 分别把components文件夹下的组件,放到dist/es/components下 和 dist/lib/components const builds = files.map(async (file: string) => { // 找到每个组件的入口文件 index.ts const input = path.resolve(compRoot, file, "index.ts"); const config = { input, plugins: [ nodeResolve(), vue({ preprocessStyles: false }), typescript(), RollupPluginPostcss({ extract: true, plugins: [Autoprefixer,cssnano()] }), commonjs(), // cleanup(), // terser({ compress: { drop_console: true }})// 压缩js代码 及删除console ], external: (id) => /^vue/.test(id) || /^@xlz-ui/.test(id), // 排除掉vue和@xlz-ui的依赖 } const bundle = await rollup(config); const options = Object.values(buildConfig).map((config) => ({ format: config.format, file: path.resolve(config.output.path, `components/${file}/index.js`), paths: pathRewriter(config.output.name), // @xlz-ui => xlz-ui/es xlz-ui/lib 处理路径 exports: "named", })); await Promise.all( options.map((option) => bundle.write(option as OutputOptions)) ); }); return Promise.all(builds); }; async function genTypes() { const project = new Project({ // 生成.d.ts 我们需要有一个tsconfig compilerOptions: { allowJs: true, declaration: true, emitDeclarationOnly: true, noEmitOnError: true, outDir: path.resolve(outDir, "./"), baseUrl: projRoot, paths: { "@xlz-ui/*": ["packages/*"], }, skipLibCheck: true, strict: false, }, tsConfigFilePath: path.resolve(projRoot, "tsconfig.json"), skipAddingFilesFromTsConfig: true, }); const filePaths = await glob("**/*", { // ** 任意目录 * 任意文件 cwd: compRoot, onlyFiles: true, absolute: true, }); // const filePathsDTS = await glob("**/*", { // // ** 任意目录 * 任意文件 // cwd: path.resolve(projRoot, "packages/types"), // onlyFiles: true, // absolute: true, // }); // filePaths.push(filePathsDTS[0]) const sourceFiles: SourceFile[] = []; await Promise.all( filePaths.map(async function (file) { if (file.endsWith(".vue")) { const content = await fs.readFile(file, "utf8"); const sfc = VueCompiler.parse(content); const { script } = sfc.descriptor; if (script) { let content = script.content; // 拿到脚本 icon.vue.ts => icon.vue.d.ts const sourceFile = project.createSourceFile(file + ".ts", content); sourceFiles.push(sourceFile); } } else { const sourceFile = project.addSourceFileAtPath(file); // 把所有的ts文件都放在一起 发射成.d.ts文件 sourceFiles.push(sourceFile); } }) ); await project.emit({ // 默认是放到内存中的 emitOnlyDtsFiles: true, }); const tasks = sourceFiles.map(async (sourceFile: any) => { const emitOutput = sourceFile.getEmitOutput(); const tasks = emitOutput.getOutputFiles().map(async (outputFile: any) => { const filepath = outputFile.getFilePath(); await fs.mkdir(path.dirname(filepath), { recursive: true, }); await fs.writeFile(filepath, pathRewriter("es")(outputFile.getText())); }); await Promise.all(tasks); }); await Promise.all(tasks); }// function copyTypes() {// const src = path.resolve(outDir, "components/"); // const copy = (module) => {// let output = path.resolve(outDir, module, "components");// console.log(src,output,module)// return () => run(`cp -r ${src}/* ${output}`);// };// return parallel(copy("es"), copy("lib"));// } async function buildComponentEntry() { const config = { input: path.resolve(compRoot, "index.ts"), plugins: [typescript(), cleanup(), terser({ compress: { drop_console: true }})// 压缩js代码 及删除console ], external: () => true, }; const bundle = await rollup(config); return Promise.all( Object.values(buildConfig) .map((config) => ({ format: config.format, file: path.resolve(config.output.path, "components/index.js"), })) .map((config) => bundle.write(config as OutputOptions)) ); } export const buildComponent = series( buildEachComponent, genTypes, // copyTypes(), buildComponentEntry );复制代码
在build/gen-types.ts
新增文件 打包ts声明文件.d.ts
import { outDir, projRoot, xlzRoot } from "./utils/paths";import glob from "fast-glob";import { Project, ModuleKind, ScriptTarget, SourceFile } from "ts-morph";import path from "path";import fs from "fs/promises";import { parallel, series } from "gulp";import { run, withTaskName,pathRewriter } from "./utils";import { buildConfig } from "./utils/config";export const genEntryTypes = async () => { const files = await glob("*.ts", { cwd: xlzRoot, absolute: true, onlyFiles: true, }); const project = new Project({ compilerOptions: { declaration: true, module: ModuleKind.ESNext, allowJs: true, emitDeclarationOnly: true, noEmitOnError: false, outDir: path.resolve(outDir, "entry"), target: ScriptTarget.ESNext, rootDir: xlzRoot, strict: false, }, skipFileDependencyResolution: true, tsConfigFilePath: path.resolve(projRoot, "tsconfig.json"), skipAddingFilesFromTsConfig: true, }); const sourceFiles: SourceFile[] = []; files.map((f) => { const sourceFile = project.addSourceFileAtPath(f); sourceFiles.push(sourceFile); }); await project.emit({ emitOnlyDtsFiles: true, }); const tasks = sourceFiles.map(async (sourceFile) => { const emitOutput = sourceFile.getEmitOutput(); for (const outputFile of emitOutput.getOutputFiles()) { const filepath = outputFile.getFilePath(); await fs.mkdir(path.dirname(filepath), { recursive: true }); await fs.writeFile( filepath, // outputFile.getText().replaceAll("@xlz-ui", "."), pathRewriter("es")(outputFile.getText()),// @xlz-ui => xlz-ui/es xlz-ui/lib 处理路径 "utf8" ); } }); await Promise.all(tasks);};export const copyEntryTypes = () => { const src = path.resolve(outDir, "entry"); const copy = (module) => parallel( withTaskName(`copyEntryTypes:${module}`, () => run( `cp -r ${src}/* ${path.resolve( outDir, buildConfig[module].output.path )}/` ) ) ); return parallel(copy("esm"), copy("cjs"));};export const genTypes = series(genEntryTypes, copyEntryTypes());复制代码
修改build/gulpfile.ts
文件 最终的样子如下
// 打包方式:串行(series) 并行(parallel)import { series, parallel } from "gulp";import { withTaskName,run } from "./utils"import { genTypes } from "./gen-types";import { outDir, xlzRoot } from "./utils/paths";//新增拷贝package.json文件const copySourceCode = () => async () => { await run(`cp ${xlzRoot}/package.json ${outDir}/package.json`);};/** * 1. 打包样式 * 2. 打包工具方法 * 3. 打包所有组件 * 4. 打包每个组件 * 5. 生成一个组件库 * 6. 发布组件 */export default series( withTaskName("clean", () => run('rm -rf ./dist')), // 删除dist目录 parallel( withTaskName("buildPackages", () => run("pnpm run -C packages/utils build") // run("pnpm run --filter ./packages --parallel build") ), withTaskName("buildFullComponent", () => run("pnpm run build buildFullComponent") ), withTaskName("buildComponent", () => run("pnpm run -C packages/theme-chalk build")), withTaskName("buildComponent", () => run("pnpm run build buildComponent")), ), parallel(genTypes, copySourceCode()), );// 任务执行器 gulp 任务名 就会执行对应的任务export * from "./full-component";export * from "./component"; //新增复制代码
执行打包 pnpm build
可能出现的问题
如果打包报错 .vue文件没有对应的声明类就在根目录新建一个types/vue-shim.d.ts
文件
declare module '*.vue' { import type { DefineComponent } from 'vue' const component: DefineComponent<{}, {}, any> export default component}复制代码
还有其他问题可以留言 看到必回 关注公众号可以第一时间收到最新文章
本文使用 文章同步助手 同步