1. 新建一个vue3+ts+vite项目
npm create vite@latest 项目名 -- --template vue-ts
2. 安装新项目的依赖,进入新项目
把App.vue的无关内容可以清空,无关的图标样式也删除。
3. 新建项目或指令文件
1、在项目中编写components文件夹下面编写组件。
2、新建一个指令的文件夹命名叫directives,在这个文件中写自己的指令。
3、在components文件夹下面建一个index.ts文件用于注册组件和指令看下面的index.ts文件的代码。
// components/index.ts
组件中index.ts文件代码
import { App, Directive } from 'vue'
import Button from './button/index.vue'
import * as directives from '@/directives/index'
export type DirectiveType = { [key: string]: Directive }
const components = [
Button
]
const install: any = function (app: App) {
// 防止已经注册过的组件重复注册
if (install.installed) return
install.installed = true
components.forEach(res => {
app.component(res.name, res)
})
// 注册指令
Object.keys(directives).forEach(res => {
app.directive(res, (directives as DirectiveType)[res])
})
}
// 导出一个install的函数或者一个对象里面有一个install的方法
export default {
install
}
4. 可以在src/App.vue中先试试自己写的组件或指令有没有问题,没有问题继续下一步。
5. 修改vite.config.ts
的配置
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from "path"
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
build: {
outDir: "@king7/resize-test", //输出文件名称
lib: {
entry: path.resolve(__dirname, "./src/components/index.ts"), //指定组件编译入口文件
name: "@king7/resize-test",
}, //库编译模式配置
rollupOptions: {
// 确保外部化处理那些你不想打包进库的依赖
external: ["vue"],
output: {
// 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
globals: {
vue: "Vue",
},
},
}, // rollup打包配置
},
})
6. 使用npm run build
打包
7. 在打包后的文件夹中
使用npm init -y
初始化,会生成一个package.json文件,然后配置package.json文件:
{
"name": "@king0725/resize-test",
"version": "0.0.1",
"description": "自测用...",
"main": "v-resize-test.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": ["v-resize-test"],
"author": "king0725",
"license": "ISC",
"private": false
}
8. 登录npm
8.1 设置npm源
如果是之前切换了淘宝镜像源的,这一步必须!!
npm config set registry=https://registry.npmjs.org
8.2 设置完后使用 npm login
登录npm
9. 最后一步:npm publish --access public
发布遇到的问题1:无法发布到私有包
npm ERR! publish Failed PUT 402
npm ERR! code E402
npm ERR! You must sign up for private packages :
这个当你的包名为@your-name/your-package时才会出现,原因是当包名以@your-name开头时,npm publish会默认发布为私有包,但是 npm 的私有包需要付费,所以需要添加如下参数进行发布:
npm publish --access public
发布遇到的问题2: npm publish包报404,is not in the npm registry错误
出现错误的原因是,在npm上的用户名是A,而包名是 @B/xxxx。
npm规定包名中,@后是用户名,我这里是B,而我的用户名是A。这就是报错的原因。
解决办法:修改包名为当前发布的用户名!!