vue3+ts+vite开发组件并上传到npm
分类: elementPlus、Vue 777 0
一、使用vite构建工具初始化vue3项目
# yarn
yarn create vite my-vue-app --template vue-ts
cd my-vue-app
yarn
yarn dev
目录结构如下图:
- lib:打包后的文件目录
- packages:组件相关内容
- src/App.vue:组件演示文件
- vite.config.ts:vite配置文件
二、组件开发导出和注册,参考element-plus导出方式
部分代码如下:
- packages\utils\index.ts
import type { AppContext, Plugin, App } from "vue";
import { NOOP } from "@vue/shared";
export * from "./utils";
export type SFCWithInstall<T> = T & Plugin;
export type SFCInstallWithContext<T> = SFCWithInstall<T> & {
_context: AppContext | null;
};
export const withInstall = <T, E extends Record<string, any>>(
main: T,
extra?: E
) => {
(main as SFCWithInstall<T>).install = (app): void => {
for (const comp of [main, ...Object.values(extra ?? {})]) {
app.component(comp.name, comp);
}
};
if (extra) {
for (const [key, comp] of Object.entries(extra)) {
(main as any)[key] = comp;
}
}
return main as SFCWithInstall<T> & E;
};
- packages\components.ts
import type { Plugin } from 'vue';
import { elementTable3 } from './components/element-table3';
export default [
elementTable3
] as Plugin[];
- packages\index.ts
// index.ts 注册组件并导出
import type { App, Plugin } from 'vue';
import Components from './components';
const INSTALLED_KEY = Symbol('INSTALLED_KEY');
export const makeInstaller = (components: Plugin[] = []) => {
const install = (app: App | any) => {
if (app[INSTALLED_KEY]) return;
app[INSTALLED_KEY] = true;
components.forEach(c => app.use(c));
};
return {
install,
};
};
export default makeInstaller([...Components]);
本地调试组件
三、配置vite.config.ts文件
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
// element-plus自动按需导入
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
// setup增加name属性为组件名称
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
vueSetupExtend()
],
build: {
outDir: 'lib',
lib: {
entry: path.resolve(__dirname, 'packages/index.ts'),
name: 'element-table3',
fileName: (format) => `element-table3.${format}.js`
},
rollupOptions: {
// 请确保外部化那些你的库中不需要的依赖
external: ['vue'],
output: {
// 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
globals: {
vue: 'Vue',
},
},
}
}
})
四、package.json文件编写
-
name:插件名称,
注意不要和已有的npm包重名了
-
private:防止意外发布私有存储库的属性,false时可以发布到npm
-
version:版本号,每次改版发布前需要修改
-
repository:代码存储库地址,可自行在github或gitee创建仓库
-
bugs:issue上报地址
五、npm上传发布
- 首次发布需要现在npm注册账号,然后本地登录、发布
npm login
npm publish
发布成功显示如下图,同时注册邮箱会有提示信息:
以上代码截图github地址:https://github.com/zjiafeng/element-table3
共 0 条评论关于 “vue3+ts+vite开发组件并上传到npm”