一、准备NPM账号
1、创建NPM账号
2、NPM登录账号
- 查询当前登录用户
npm whoami
- npm 登录
npm login
npm 的registry需要设置为 “https://registry.npmjs.org/”
- 输入npm的账号
- 输入npm的密码
- 输入npm发送的邮箱验证码
- 登录完成
3、将代码推送至NPM
- npm publish
二、创建项目
1、创建一个VUE项目
2、修改package.json
- name 项目名称
- description 作者
- keywords 搜索的关键词
- version 版本号(每次升级推送都需要增加修改)
- license 许可证(MIT、ISC、BSD等)
- private 是否私有 设置为true的话NPM则发布不成功
- files 需要推送的文件夹
- main 入口文件
- scripts 运行命令
- repository 代码存储位置
- 例:
{
"name": "gy-common",
"description": "gy",
"keywords": [
"gy"
],
"version": "0.2.43",
"license": "MIT",
"private": false,
"files": [
"lib",
"example"
],
"main": "lib/gy-common.umd.js",
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"push": "vue-cli-service build --target lib -name gyCommon --dest lib src/plugins/index.js && npm publish",
"lib": "vue-cli-service build --target lib -name gyCommon --dest lib src/plugins/index.js",
},
"repository": {
"type": "git",
"url": "git@github.com:guoyao132/gy-commom.git"
},
"dependencies": {
},
"devDependencies": {
"@vue/cli-plugin-babel": "~4.5.13",
"@vue/cli-plugin-eslint": "~4.5.13",
"@vue/cli-plugin-router": "~4.5.13",
"@vue/cli-plugin-vuex": "~4.5.13",
"@vue/cli-service": "~4.5.13",
"@vue/compiler-sfc": "^3.0.0",
"babel-eslint": "^10.1.0",
"core-js": "^3.6.5",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^7.0.0",
"vue": "^3.0.0",
"vue-router": "^4.0.0-0",
"vuex": "^4.0.0-0"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
3、创建入口文件
- 在src下创建plugins文件夹,并创建index.js
- 在index.js文件中加载需要的文件,并将其export
- 例:
import common from './common'
import './css/reset.css'
let install = (app, option) => {
const version = Number((app.version || '0').split('.')[0])
if(version >= 3){
app.config.globalProperties.$gyCom = common;
}else{
app.prototype.$gyCom = common;
}
}
export {install};
export {common}
export default {
install,
common,
};
4、在package.json中添加命令
- “lib”: “vue-cli-service build --target lib -name [包名|gyCommon] --dest [输出文件夹|lib] [入口文件|src/plugins/index.js]”,
- 例:
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lib": "vue-cli-service build --target lib -name gyCommon --dest lib src/plugins/index.js",
}
- 配置打包后直接推送(前提是已经NPM已登录)
“lib”: “vue-cli-service build --target lib -name gyCommon --dest lib src/plugins/index.js && npm publis”,