1. 需求
項目中要求對外提供vue的公共組件,但是不能提供源碼,於是就需要用通過對單個組件打包后對外提供。發布到npm上供項目下載使用。
2. 新建項目
Vue-cli3創建一個項目:vue create vue-project
3. 封裝組件
在views中新建一個組件的文件夾(你可以自己定義自己的組件位置),新建組件Manager.vue和對應的一個index.js文件,如下圖
index.js的內容如下:
1 import Manager from './Manager.vue' 2 3 if (typeof window !== 'undefined' && window.Vue) { 4 window.Vue.component('Manager', Manager) 5 } 6 //為組件添加 install 方法 7 Manager.install = function(Vue){ 8 Vue.component(Manager.name, Manager) 9 } 10 export default Manager
4. 在package.json添加打包組件命令配置
執行打包命令:npm run build-component
完成后在項目根目錄會生成dist文件夾,里面就是打包生成的組件的壓縮文件,還有一個demo.html示例文件。
提示:package.json中的name一般是根據項目名稱命名的,但是在打包的時候你可以改成你想要的組件的名稱,比如我會改成:manager-component。
5. 測試打包完成的組件
在package.json添加配置
執行命令:npm pack
在項目中會生成一個manager-component-0.1.0.tgz的壓縮文件。
6. 在其他項目中引用
1)將壓縮包放到某個文件夾下,執行命令: npm install 壓縮包的絕對路徑\manager-component-0.1.0.tgz
在main.js中import Manager from ‘manager-component’
全局注冊組件Vue.component(‘manager-component’, Manager)
7. 發布到npm
1)注冊一個npm賬號,執行命令:npm login登錄,執行命令npm publish發布
2)在main.js中import Manager from ‘manager-component’ ,
全局注冊組件Vue.component(‘manager-component’, Manager)。
注意:全局注冊組件的時候用Vue.use(Manager)可能不成功,我的沒有成功,於是用Vue.component(‘manager-component’, Manager)注冊一下組件就能用了。