Distribute Vue component with zero-config

EGOIST
2 min readJan 19, 2017

--

As vue-cli 2.8.0 just released early this morning, I’d like to introduce how to use its new command vue build to distribute a reusable component. Also as a quick glance at the new shiny feature.

I want to build a Counter component which is the “Hello World” in UI land.

Start from scratch

With vue-cli it’s really simple to fresh-start a new project:

mkdir vue-counter
cd vue-counter
touch Counter.vue && $editor . # open with your desired editor

Then edit Counter.vue :

<template>
<div class="v-counter">
{{ count }}
</div>
</template>
<script>
export default {
props: {
start: {
default: 0,
type: Number
},
inc: {
default: 1,
type: Number
},
timeout: {
default: 1000,
type: Number
}
},
data() {
return {
count: this.start
}
},
created() {
setInterval(() => {
this.count += this.inc
}, this.timeout)
}
}
</script>
<style>
.v-counter {
background-color: #1d89ff;
padding: 20px;
display: flex;
justify-content: center;
align-items: center;
font-size: 26px;
}
</style>

And you’re all set! Now you have a Counter which starts from 0 and increase by 1 per second by default.

You can run vue build Counter.vue to test it out in browser.

Finally, you can deploy the example of this component and the UMD build for it as well!

# build the example
vue build Counter.vue --dist dist-example
# maybe publish example to github-pages
gh-pages -d dist-example
# build the component itself in UMD format
vue build Counter.vue --lib
# make sure the main field
# in package.json is pointed to `./dist/Counter.js`
# the CSS file can be found at `./dist/Counter.css`
npm publish

Now, after you publish it to npm, you can do import Counter from 'you-counter-component' in your app, or access window.Counter in browser.

Conclusion

So far we haven’t even used a configuration file, simply CLI options suit our need for now. But of course you can! vue build allows you to freely customize the config and webpack config, check out docs at https://github.com/vuejs/vue-cli/blob/master/docs/build.md

--

--

EGOIST
EGOIST

Responses (1)