找回密码
 立即注册
首页 业界区 业界 vite如何打包vue3插件为JSSDK

vite如何打包vue3插件为JSSDK

赖秀竹 4 天前
安装vite
  1. npm create vite@latest
复制代码
你还可以通过附加的命令行选项直接指定项目名称和你想要使用的模板。例如,要构建一个 Vite + Vue + ts 项目,运行:
  1. # npm 7+,需要添加额外的 --:
  2. npm create vite@latest my-vue-app -- --template vue-ts
复制代码
查看 create-vite 以获取每个模板的更多细节:vanilla,vanilla-ts, vue, vue-ts,react,react-ts,react-swc,react-swc-ts,preact,preact-ts,lit,lit-ts,svelte,svelte-ts,solid,solid-ts,qwik,qwik-ts。
你可以使用 . 作为项目名称,在当前目录中创建项目脚手架。
vite官网:https://cn.vitejs.dev/guide/
环境配置

在src中添加vue-shim.d.ts文件及内容:
  1. /* eslint-disable */
  2. declare module '*.vue' {  
  3.     import { DefineComponent } from 'vue';  
  4.     const component: DefineComponent<{}, {}, any>;  
  5.     export default component;  
  6. }
复制代码
目的是告诉TS如何处理.vue文件。
我们使用 DefineComponent 类型来注解 .vue 文件的默认导出,这是 Vue 3 中用于定义组件的类型。这个类型接受组件的 props、context 和其他选项作为泛型参数,但在这个简单的声明中,我们使用了空对象 {} 和 any 作为占位符,因为它们在这里主要是为了类型注解的完整性,并不会在运行时影响组件的行为。
SDK基础框架代码

sdk/libApp.vue:
  1. <template>
  2.   <p>msg:{{ msg }}</p>
  3.   <p>appid:{{ appid }}</p>
  4.   
  5.     <button type="button" @click="increment">count is {{ count }}</button>
  6.   
  7. </template>
复制代码
sdk/main.ts:
  1. import { createApp } from "vue";
  2. import libApp from './libApp.vue';
  3. type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
  4. type VueApp = ReturnType<typeof createApp>;  
  5. interface IMyLib {
  6.     el: string;
  7.     success?: (...args: any[]) => any;
  8.     fail?: (...args: any[]) => any;
  9.     [key: string]: any;
  10. }
  11. class MyLib {
  12.     app: VueApp;
  13.     el: string = '#app';
  14.    /**
  15.     * 构造函数
  16.     *
  17.     * @param appInstance VueApp 实例对象
  18.     * @param options IMyLib 接口对象,包含可选参数 el,默认值为 '#app'
  19.     */
  20.    constructor(appInstance: VueApp,{el = '#app'}: IMyLib) {
  21.     this.app = appInstance;
  22.     this.el = el;
  23.     this.render();
  24.    }  
  25.    /**
  26.     * 渲染组件
  27.     *
  28.     * @returns 无返回值
  29.     */
  30.    render() {
  31.     this.app.mount(this.el);
  32.    }
  33.    
  34.    /**
  35.     * 为Vue应用实例添加全局配置
  36.     *
  37.     * @param app Vue应用实例
  38.     * @param options 入参选项
  39.     */
  40.    static globalConfig(app: VueApp,options: IMyLib) {
  41.      // 为app实例添加全局属性
  42.      app.config.globalProperties.$options = options;
  43.    }
  44.    /**
  45.     * 配置MyLib实例
  46.     *
  47.     * @param options IMyLib类型的配置项
  48.     * @returns 返回Promise<MyLib>,表示MyLib实例的Promise对象
  49.     */
  50.    static config(options: IMyLib) {
  51.     const opts: IMyLib = {
  52.         success: () => {},
  53.         fail: () => {},
  54.         ...options
  55.     }
  56.      // 下面可以校验参数的合理性、参数的完整性等
  57.      if(!opts.appid) {
  58.         if (typeof opts.fail === 'function') {  
  59.             opts.fail('appid is required');  
  60.             return;
  61.         }
  62.         
  63.     }
  64.     const app = createApp(libApp);
  65.     app.use({  
  66.         install(app: VueApp, opts: IMyLib) {  
  67.             MyLib.globalConfig(app, opts);  
  68.         }  
  69.     }, opts);
  70.     const viteTest = new MyLib(app,opts);
  71.     if (typeof opts.success === 'function') {  
  72.        opts.success(viteTest);  
  73.     }
  74.    }
  75. }
  76. export default MyLib;
复制代码
插件安装、构建配置、编译

插件安装

安装vite-plugin-css-injected-by-js插件,其作用:打包时把CSS注入到JS中。
  1. npm i vite-plugin-css-injected-by-js -D
复制代码
安装vite-plugin-dts插件,其作用:生成类型声明文件。
当然,也有人在 issue 中提出希望 Vite 内部支持在库模式打包时导出声明文件,但 Vite 官方表示不希望因此增加维护的负担和结构的复杂性。
  1. npm i vite-plugin-dts -D
复制代码
vite.config.ts

vite.config.ts配置如下:
  1. import { defineConfig } from 'vite'
  2. import vue from '@vitejs/plugin-vue'
  3. import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js'
  4. import dts from "vite-plugin-dts";
  5. // https://vitejs.dev/config/
  6. export default defineConfig({
  7.   plugins: [
  8.     vue(),
  9.     cssInjectedByJsPlugin(),
  10.     dts({
  11.     // 指定 tsconfig 文件
  12.       tsconfigPath: 'tsconfig.build.json',
  13.       rollupTypes: true
  14.     })
  15. ],
  16.   build: {
  17.     lib: {
  18.       entry: 'sdk/main.ts',
  19.       formats: ['es'],
  20.       name: 'myLib',
  21.       fileName: 'my-lib',
  22.     },
  23.     rollupOptions: {
  24.       // 确保外部化处理那些你不想打包进库的依赖
  25.       external: ['vue'],
  26.       output: {
  27.         // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
  28.         globals: {
  29.           vue: 'Vue',
  30.         },
  31.       },
  32.     },
  33.   }
  34. })
复制代码
添加tsconfig.build.json代码:
  1. {
  2.     "compilerOptions": {
  3.       "target": "ES2020",
  4.       "useDefineForClassFields": true,
  5.       "module": "ESNext",
  6.       "lib": ["ES2020", "DOM", "DOM.Iterable"],
  7.       "skipLibCheck": true,
  8.       "declaration": true,           
  9.       "declarationDir": "./dist/types",
  10.   
  11.       /* Bundler mode */
  12.       "moduleResolution": "bundler",
  13.       "allowImportingTsExtensions": true,
  14.       "isolatedModules": true,
  15.       "moduleDetection": "force",
  16.       "noEmit": true,
  17.       "jsx": "preserve",
  18.   
  19.       /* Linting */
  20.       "strict": true,
  21.       "noUnusedLocals": true,
  22.       "noUnusedParameters": true,
  23.       "noFallthroughCasesInSwitch": true
  24.     },
  25.     "include": ["sdk/**/*.ts","sdk/**/*.vue"],
  26.   }
  27.   
复制代码
vite-plugin-dts地址:https://www.npmjs.com/package/vite-plugin-dts
库包编译

执行:
  1. npm run build
复制代码
在dist下存在如下构建文件:

  • my-lib.d.ts(声明文件)
  • my-lib.js(库文件)
生成的my-lib.d.ts文件内容如下:
  1. import { createApp } from 'vue';
  2. declare interface IMyLib {
  3.     el: string;
  4.     success?: (...args: any[]) => any;
  5.     fail?: (...args: any[]) => any;
  6.     [key: string]: any;
  7. }
  8. declare class MyLib {
  9.     app: VueApp;
  10.     el: string;
  11.     /**
  12.      * 构造函数
  13.      *
  14.      * @param appInstance VueApp 实例对象
  15.      * @param options IMyLib 接口对象,包含可选参数 el,默认值为 '#app'
  16.      */
  17.     constructor(appInstance: VueApp, { el }: IMyLib);
  18.     /**
  19.      * 渲染组件
  20.      *
  21.      * @returns 无返回值
  22.      */
  23.     render(): void;
  24.     /**
  25.      * 为Vue应用实例添加全局配置
  26.      *
  27.      * @param app Vue应用实例
  28.      * @param options 入参选项
  29.      */
  30.     static globalConfig(app: VueApp, options: IMyLib): void;
  31.     /**
  32.      * 配置MyLib实例
  33.      *
  34.      * @param options IMyLib类型的配置项
  35.      * @returns 返回Promise<MyLib>,表示MyLib实例的Promise对象
  36.      */
  37.     static config(options: IMyLib): void;
  38. }
  39. export default MyLib;
  40. declare type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
  41. declare type VueApp = ReturnType<typeof createApp>;
  42. export { }
复制代码
验证插件包

由于是在本地构建生成的文件在本地,没有上传到npm,把本地生成的声明文件可以拷贝到src下或者types目录下。
我们把my-lib.js文件也拷贝到src目录下进行验证,我们调整src/App.vue下代码如下:
  1. <template>
  2.   
  3.    
  4.    
  5.       <img src="https://www.cnblogs.com/vite.svg"  alt="Vite logo" />
  6.    
  7.    
  8.       <img src="https://www.cnblogs.com/./assets/vue.svg"  alt="Vue logo" />
  9.    
  10.   
  11.   <HelloWorld msg="Vite + Vue" />
  12. </template>
复制代码
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
1.jpg
2.jpg
您需要登录后才可以回帖 登录 | 立即注册