First of all big up to those who develop and publish vue components. You make work very easy and simple for us. Most components are just an npm install away.
However I would like to draw your attention to one small aspect of exporting components. Lets look at how we normally expose components to be publishable. Assuming we have a hello world component
<template> | |
<div> | |
<h1>Hello World</h1> | |
</div> | |
</template> | |
<script> | |
export default { | |
name: 'hello-world' | |
} | |
</script> |
Lets expose it to be the outside world so that we can publish to npm
import HelloWorld from './components/HelloWorld.vue' | |
export default { | |
install: function (Vue, options) { | |
Vue.component('hello-world', HelloWorld); | |
}, | |
} |
With this when someone installs your vue component he/she has to import it and register it to the global scope.
import Vue from 'vue' | |
import HelloWorld from 'helloworld' | |
Vue.use(HelloWorld) //hello-world is registered to the global scope |
This approach is okay if the component is going to be used in many places of the application. If not it would be polluting the global scope. But if someone using your component wants to use it on a local component once he has to resort to importing it like this
import HelloWorld from 'helloworld/src/components/HelloWorld.vue'
Which is not really ideal and not straight forward. The best practice would be to provide the user a way to both import it globally and locally at the same time with minimal effort. Not having to deal with the internal structure of your application.
The ideal imports should be
// How a user may choose to use your awesome component. | |
import Vue from 'vue' | |
import HelloWorld from 'helloworld' | |
Vue.use(HelloWorld) // If this component is going to be used in many places | |
//... in component | |
import { HelloWorld } from 'helloworld' // this is if he needs to use it only on one component | |
export default { | |
components: { | |
HelloWorld | |
} | |
} |
To achieve this there is only one line you need to add. One that is being neglected by most component developers.
When you export your component please remember to include this line.
import HelloWorld from './components/HelloWorld.vue' | |
export default { | |
install: function (Vue, options) { | |
Vue.component('hello-world', HelloWorld); | |
}, | |
} | |
// this line is what makes it possible for the user of the | |
// component to be able to use it in a local component if he needs to | |
export { HelloWorld } |
If this post was helpful please share it and stay tuned for my other articles. You can follow me on GitHub and LinkedIn. If you have any ideas and improvements feel free to share them with me.
Happy coding!
Top comments (0)