美文网首页前端Vue专辑
vue开发公共组件并发布到npm

vue开发公共组件并发布到npm

作者: 谦君子丶温如玉 | 来源:发表于2019-01-29 16:35 被阅读6次

写在前面

作为一名合格的前端开发,想必大家都会有过这样的烦恼:上个项目写过这个功能(组件),这个项目又有相似的需求,又要撸一遍,费时费力还烦人。。。于是我想到了做成公共组件发布到npm上,下个项目使用时直接npm install xxx岂不是美滋滋?想法已经有了,那就开始着手干吧~~

\color{red}{本博客以创建一个element-ui公共提示信息组件为例~}
\color{red}{项目名称:public-element-prompt-component}

一、搭建精简版(webpack-simple)vue开发模板

注:随着vue-cli3的发布,vue init webpack/webpack-simple xxx的语法已经被新版 vue create xxx所取代,因此,如果你使用的是vue-cli3,需要先行安装@vue/cli-init以便使用vue-cli 2.x版本语法:
vue -V //查看vue-cli版本
npm install -g @vue/cli-init //全局安装@vue/cli-init

官方参考文档:传送门

开始创建vue开发模板:
vue init webpack-simple public-element-prompt-component //创建webpack-simple模板项目

创建成功图示如下:

image.png
创建完成后进入项目目录,安装相关依赖 (cnpm install),并运行(npm run dev)测试项目是否成功运行。出现以下界面则表示项目创建成功:
image.png
image.png

二、开始开发组件

src目录下新建文件夹(名字随意),并新建一个.vue文件,图示如下:

image.png

文件代码如下:

<template>
    <div class="PublicComponent"></div>
</template>

<script>
export default {
    name: 'PublicComponent',
    data() {
        return {

        }
    },
    props:{
        msgConfig:Object,
        confirmConfig:Object,
        promptConfig:Object
    },
    watch: {
        msgConfig: function (val, oldVal) {
            if (val != oldVal) {
                this.showMassage(val);
            }
        },
        confirmConfig: function (val, oldVal) {
            if (val != oldVal) {
                this.showConfirmModal(val);
            }
        },
        promptConfig: function (val, oldVal) {
            if (val != oldVal) {
                this.showPromptModal(val);
            }
        }
    },
    methods: {
        showMassage(config) {
            this.$message(config);
        },
        showConfirmModal(config) {
            this.$confirm(config.message, config.title, config.options ? config.options : {}).then(config.yesCallback).catch(config.cancelCallback ? config.cancelCallback : () => { });
        },
        showPromptModal(config) {
            this.$prompt(config.message, config.title, config.options ? config.options : {}).then(config.yesCallback).catch(config.cancelCallback ? config.cancelCallback : () => { });
        }
    }
}
</script>

三、在组件平级目录下新增index.js文件

代码如下:

import PublicComponent from './PublicComponent.vue'

// Declare install function executed by Vue.use()
export function install(Vue) {
    if (install.installed) return;
    install.installed = true;
    Vue.component('PublicComponent', PublicComponent);
}

// Create module definition for Vue.use()
const plugin = {
    install,
};

// Auto-install when vue is found (eg. in browser via <script> tag)
let GlobalVue = null;
if (typeof window !== 'undefined') {
    GlobalVue = window.Vue;
} else if (typeof global !== 'undefined') {
    GlobalVue = global.Vue;
}
if (GlobalVue) {
    GlobalVue.use(plugin);
}

export default PublicComponent;

官网参考文档:传送门

四、修改package.json等配置文件

package.json文件配置图示如下:

image.png
webpack.config.js文件配置,主要修改入口(entry)及出口信息(output):
···
module.exports = {
 // entry: './src/main.js',
  entry: './src/component/index.js',
  output: {
      path: path.resolve(__dirname, './dist'),
      publicPath: '/dist/',
      // filename: 'build.js'
      filename: 'public-component.js',//与package.json中main相对应
      library: 'Public-component',
      libraryTarget: 'umd',
      umdNamedDefine: true
  }
...
}

相关配置参考:传送门

五、打包测试

以上步骤完成后,我们可以进行打包测试了:

npm run build //打包

打包完成图示如下:


image.png

六、发布到npm

首先你需要拥有一个npm账号!需要拥有一个npm账号!拥有一个npm账号!
重要的事情说三遍~~
附上npm账号注册地址:传送门

账号注册完成后就是发布流程了:

npm login //登录npm,需要正确填写用户名、密码及邮箱

npm publish //发布到npm
发布成功图示如下: image.png

七、测试使用组件

发布成功后,你的注册邮箱会受到来自npm的邮件,提示你的npm包已经成功发布。这时候我们可以去npmcnpm搜索上传的包:
npm地址:传送门
cnpm地址:传送门

image.png

在其他项目中使用该组件:

cnpm install public-element-prompt-component --save-dev  //安装发布的npm包

用于测试的test项目,目录如下:

image.png
由于项目依赖于element-ui,因此main.js需要进行修改
相关静态资源文件,如index.css,字体文件等,请放在static目录下,并在index.html中引入。mian.js具体代码如下:
import Vue from 'vue'
import App from './App.vue'
import { Button, Message, MessageBox } from 'element-ui';

Vue.use(Button);

Vue.prototype.$message = Message;
Vue.prototype.$confirm = MessageBox.confirm;
Vue.prototype.$prompt = MessageBox.prompt;


Vue.config.productionTip = false

new Vue({
    render: h => h(App),
}).$mount('#app')

App.vue代码如下:

<template>
    <div class="hello">
        <el-button @click="showComponent" type="danger" plain>删除</el-button>
        <publicComponent :msgConfig="publicComponentObj.msgConfig" :confirmConfig="publicComponentObj.confirmConfig"></publicComponent>
    </div>
</template>

<script>
import PublicComponent from 'public-element-prompt-component'
export default {
    name: 'HelloWorld',
    props: {
        msg: String
    },
    data() {
        return {
            publicComponentObj: {
                confirmConfig: {},
                msgConfig: {},
            }
        }
    },
    methods: {
        showComponent() {
            const tempObj = {
                message: `确认移出选中成员吗?`,
                title: '提示',
                options: {
                    type: 'warning'
                },
                yesCallback: () => {
                    const tempMsgObj = {
                        message: '删除成功',
                        type: 'success',
                        showClose: true,
                        duration: 3000
                    }
                    this.publicComponentObj.msgConfig = tempMsgObj;
                }
            }
            this.publicComponentObj.confirmConfig = tempObj;
        }
    },
    components: {
        PublicComponent
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

执行效果如下:

image.png
image.png
\color{red}{注:相关vue-cli3新建项目请参考以下官方文档:}
官方文档:传送门

结束语

后续如果有版本更新,只需要修改package.json中的版本号重新发布即可~~

以上就是关于开发vue公共组件并发布到npm的操作步骤,有什么不足之处希望大家不吝评价~~
水平有限,各位看官不要嫌弃哈~~
\color{red}{最后附上github地址:}传送门

感谢浏览~

相关文章

网友评论

    本文标题:vue开发公共组件并发布到npm

    本文链接:https://www.haomeiwen.com/subject/flrxsqtx.html