kylin

醉里论道,醒时折花。

kylin

vue插件的打包与发布

初始化项目

以我刚发布的vue-calendar组件为例

开发插件用webpack-simple 模板比较合适

1
2
3
vue init webpack-simple vue-calendar
cd vue-calendar
npm install

在跟目录下新建test文件夹用于开发测试

我这里将原本位于src文件夹下的main.js以及App.vue文件转移到了test文件夹下

将插件源码放在src文件夹下,插件入口为src/calendar/main.js

修改 webpack.config.js 文件

根据不同的命令(环境变量)设置不同的入口与输出文件,保证npm run devnpm run build两个命令都为可用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var path = require('path')
var webpack = require('webpack')
//...根据环境变量(package.json script中设置)...
var entry = './test/main.js'
var outputFileName = 'build.js'
if (process.env.NODE_ENV === 'production') {
entry = './src/calendar/main.js'
outputFileName = 'vue-calendar.js'
}
//......
module.exports = {
//entry改为变量
entry: entry,
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
//filename
filename: outputFileName,
//library与libraryTarget一定要添加,否则import进来的对象为空
library: 'vue-calendar',
libraryTarget: 'umd'
},
//...
}

这里要注意非常重要的一点,webpack默认你构建的内容是一个应用而非library,如果不设置library将会导致你在使用该插件的时候import进来的对象为空。

A webpack bundle does not expose your exports by default, as it assumes that you’re building an app and not a library (which is the far more common use of webpack). You can create a library by configuring output.library and output.libraryTarget 参考一 参考二

修改package.json

使用npm run build或其他方式打包。

  • private设置为false
  • main设置为打包产出的文件路径
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
"name": "himmas-vue-calendar",
"description": "A calendar component for Vue.js",
"version": "1.1.2",
"author": "kylin-z <kailinzhou@yeah.net>",
"license": "MIT",
"scripts": {
"dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot",
"build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
},
"private": false,
"main": "dist/vue-calendar.js",
"repository": {
"type": "git",
"url": "https://github.com/kylin-z/vue-calendar.git"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
],
"keywords": [
"calendar",
"custom",
"vue"
]
//...
}

发布到npm

  • 在控制台登录npm账号

    1
    $ npm login
  • 发布(每次发布需要更新version)

    1
    $ npm publish