背景
最近做的项目需要开发插件功能,要求可以从服务器上加载,那就需要加载动态组件。但是所有需要加载的组件都是动态获取和实例化的,需要作为插件加载进来。那么这些插件如何打包为单独的js文件呢?由于项目用的vue-cli 脚手架,发现了构建目标,打包为库的功能,完美解决痛点。
vue-cli构建默认是应用模式,但是build时可以通过 --target 选项指定不同的构建目标。它允许你将相同的源代码根据不同的用例生成不同的构建。内置的有构建为一个库和构建为一个Web Components 组件2种方式。
1. 项目中用到的是第一种构建为一个库的方式。
在src/views/plugins/components/Demo 下写了个demo.vue示例插件,执行yarn build --target lib --name demo src/views/plugins/components/Demo/Index.vue
命令(demo
表示打包的库名及打包后的文件名字,src/views/plugins/components/Demo/Index.vue
表示库的入口文件),控制台会告诉我们正在构建为一个库:

构建库成功:

然后会发现项目下会生成一个dist文件夹,各种文件格式官网都有说明:

demo.html 里面连示例都写好了,直接运行就可以看到效果:

这样打包好后的文件就可以上传到服务器上,前端从服务器拉取代码通过下面代码实例化就好了。

- Web Components 组件
执行命令:
yarn build --target wc --name plugin-demo src/views/plugins/components/Demo/Index.vue
plugin-demo 表示web组件的名称,以-的形式更直观更符合规范(这点和库名有所区别),生成的组件可在普通 HTML 中或者其它任何框架中使用。


和构建库一样,编译成功后会生成一个dist文件夹,同样给出了示例,太贴心啦~

注:
两种打包方式都是将vue排除在外的,使用之前需引入vue
网友评论