vue-cli3发布自定义组件到npm
1.创建项目
使用vue-cli3脚手架创建Vue项目后,再创建一个名为components的文件夹,里面用于存放自定义的组件
2.修改配置
修改vue配置文件部分内容:vue.config.js,配置如下:
'use strict'
// vue.config.js
module.exports = {
pages: {
index: {
// page 的入口
entry: 'src/main.js',
// 模板来源
template: 'public/index.html',
// 输出文件名
filename: 'index.html'
}
}
}
3.开发并注册组件
在components文件夹中存放自己的组件,并写一个index.js导出该文件夹下所有组件,index.js的内容如下:
// components/index.js
const install = (Vue)=>{
const requireComponent = require.context(".",true,/\.vue/);
requireComponent.keys().forEach(fileName=>{
const config = requireComponent(fileName);
Vue.component(config.default.name,config.default);
})
}
export default {
install
}
作为测试,可以在完成之后,在入口文件main.js中导入components/index.js,并在vue文件中测试使用。
4.打包组件
vue-cli 3.x 提供了一个库文件打包命令
主要需要四个参数:
-
target: 默认为构建应用,改为 lib 即可启用构建库模式
-
name: 输出文件名
-
dest: 输出目录,默认为 dist,这里我们改为 lib
-
entry: 入口文件路径,默认为 src/App.vue,这里改为 packages/index.js
基于此,在 package.json 里的 scripts 添加一个 lib 命令
// pageage.json
{
"scripts": {
"lib": "vue-cli-service build --target lib --name ysl-input --dest lib src/components/index.js"
}
}
然后执行 npm run lib 命令,编译组件
5.准备发布
1)首先需要在 package.json 添加组件信息
name: 包名,该名不能和已有的名称冲突;
version: 版本号,不能和历史版本号相同;
description: 简介;
main: 入口文件,应指向编译后的包文件;
keyword:关键字,以空格分割;
author:作者;
private:是否私有,需要修改为 false 才能发布到 npm;
license:开源协议。
{
"name": "ysl-ui",
"version": "0.1.0",
"description": "ysl-ui",
"main": "lib/ysl-input.umd.js",
"private": false,
"license": "MIT",
"author": "ysl",
......
}
2)然后创建 .npmignore 文件,设置忽略文件
该文件的语法和 .gitignore 的语法一样,设置发布到 npm 时忽略哪些目录或文件
.DS_Store
node_modules/
examples/
packages/
public/
vue.config.js
babel.config.js
*.map
*.html
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw*
6.发布
如果以前改过 npm 的镜像地址,比如使用了淘宝镜像,就先改回来,命令如下:
npm config set registry http://registry.npmjs.org
如果没有 npm 账户,可以通过 npm adduser 命令创建一个账户,或者到 npm 官网注册
如果在官网注册的账户,或者以前就有账户,就使用 npm login 命令登录
具体流程可以参考官方文档
在发布之前,一定要确保组件已经编译完毕,而且 package.json 中的入口文件(main)的路径正确
一切就绪,发布组件:
npm publish
7.结束
over~