前言
当我们开发多个项目后,会产生一些高度耦合的组件,这个是时候可以将一些不需要修改,或很少需要修改的组件提取出来,发布到npm官网,成为一个插件,减少项目包体积,防止误改等等。
一、使用模板
使用现成模板项目,替换其中组件,install相关依赖。发布详情请查看项目内部README.md文件
二,重新搭建
1、创建项目
npm install -g @vue/cli 搭建工程
vue create llgtfoo-components-boxs 创建项目
2、在项目中添加组件库文件夹
在根目录下新建一个plugins文件夹,用来放组件,项目文件结构为:
3、修改vue.config.js文件
const path = require('path')
module.exports = {
// 修改 pages 入口
pages: {
index: {
entry: 'src/main.js', // 入口
template: 'public/index.html', // 模板
filename: 'index.html' // 输出文件
}
},
// 扩展 webpack 配置
chainWebpack: config => {
// @ 默认指向 src 目录
// 新增一个 ~ 指向 plugins
config.resolve.alias
.set('~', path.resolve('plugins'))
// 把 plugins 加入编译,因为新增的文件默认是不被 webpack 处理的
config.module
.rule('js')
.include.add(/plugins/).end()
.use('babel')
.loader('babel-loader')
.tap(options => {
// 修改它的选项...
return options
})
}
}
4、编写组件
统一暴露组件、指令、过滤器:
import Demo from "./components/demo"
import Transfer from "./components/transfer"
const components = [Demo, Transfer]; //组件
// const directives = [] // 指令
// const filters = [ ] //过滤器
//定义install方法,Vue作为参数
const install = Vue => {
console.log(Vue)
//判断是否安装,安装过就不用继续执行
if (install.installed) return;
install.installed = true;
//遍历注册所有组件
components.map(component \=> Vue.component(component.name, component));
//遍历注册所有指令
// directives.map(directives => Vue.use(directives));
//遍历过滤器
// filters.map(filters => Vue.use(filters));
};
//检测到Vue再执行
if (typeof window !== "undefined" && window.Vue) {
install(window.Vue);
}
export default {
install,
//所有组件,必须具有install方法才能使用Vue.use()
...components
};
5、库模式打包
在package.json文件中的"scripts"字段里添加以下内容:
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lib": "vue-cli-service build --target lib --name llgtfoo-components-box -dest lib plugins/index.js",
"lint": "vue-cli-service lint"
},
6、.gitignore文件,
把包的一些测试文件过滤掉,最终打包只留下直接封装的文件,即plugins中封装的暴露组件
.DS_Store
node_modules
/dist
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
src/
plugins/
public/
vue.config.js
babel.config.js
*.map
*.html
7. 发布包
在终端执行,第一次发布:
npm login 登录npm官网
npm run lib 打包
npm publish 发布
更新版本:
npm version patch 修改版本号version
npm publish 发布
patch:小变动,比如修复bug等,版本号变动 \*\*v1.0.0->v1.0.1\*\*
minor:增加新功能,不影响现有功能,版本号变动 \*\*v1.0.0->v1.1.0\*\*
major:破坏模块对向后的兼容性,版本号变动 \*\*v1.0.0->v2.0.0\*\*
卸载包:
npm unpublish <package-name> -f
8、使用包
npm i xxxxxxxx
9、项目中实际使用
9.1 安装依赖
npm i bk-element-ui