utils 利用 unbuild 打包
安装包
在utils目录下面安装unbuild
bash
pnpm add unbuild -Dutils 目录
bash
├── src
│ ├── index.ts(入口文件)
│ ├── tools
│ ├── index.ts 工具文件
├── build.config.ts 打包配置文件
├── package.json
├── tsconfig.jsontsconfig.json
json
{
"compilerOptions": {
"target": "esnext",
"useDefineForClassFields": true,
"module": "esnext",
"moduleResolution": "node",
"isolatedModules": true,
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["esnext", "dom", "dom.iterable", "scripthost"],
"skipLibCheck": true,
"baseUrl": ".",
"paths": {}
}
}package.json
增加打包命令 build ,stub
增加 main module types 字段
json
{
"name": "@vue3-my-component/utils",
"version": "1.0.0",
"description": "",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "unbuild",
"stub": " unbuild --stub"
},
"keywords": [],
"author": "",
"license": "ISC",
"packageManager": "pnpm@10.15.1",
"devDependencies": {
"@vue/tsconfig": "^0.8.1",
"typescript": "^5.9.3",
"unbuild": "^3.6.1",
"vite": "^7.3.1",
"vitest": "^4.0.17"
},
"dependencies": {
"vue": "^3.5.26"
}
}build.config.ts
ts
import { defineBuildConfig } from "unbuild";
export default defineBuildConfig({
// 忽略警告
failOnWarn: false,
// 构建的入口文件
entries: ["src/index.ts"],
// 是否生成声明文件
declaration: true,
// 是否清理输出目录
clean: true,
// 打包配置
rollup: {
// 打包格式 两种都打 mjs,cts
// mjs 主要是 引入的时候 是import { xxx } from 'xxx' 格式
// cjs 主要是 引入的时候 是const { xxx } = require('xxx') 格式
emitCJS: true,
},
});src/index.ts
ts
export * from "./tools";src/tools/index.ts
ts
// 用于判断传入的值是否为字符串类型。
export const isStr = (str: any): str is string => typeof str === "string";
// 用于判断传入的值是否为数字类型。
export const isNum = (num: any): num is number => typeof num === "number";打包
bash
npm run build调用
src/ui 下面安装
- package.json
bash
"dependencies": {
"vue": "^3.5.26",
"@vue3-my-component/utils":"workspace:*"
}执行命令
bash
pnpm add @vue3-my-component/utils调用
vue
<script setup lang="ts">
import { isStr, isNum } from "@vue3-my-component/utils";
defineOptions({
name: "LButton",
});
const handleClick = () => {
window.alert(isStr("123"));
window.alert(isNum("123"));
};
</script>
<template>
<button @click="handleClick">惦记我</button>
</template>
<style scoped></style>