In our vue applications, we might want to declare some components to be global components so that we can use them anywhere in our application without importing them each time. Let's see how to do that.
Which Components should be global.
The type of components we want to declare as global components are those ones we use regularly and in different areas in our applications. The reason?
Example:
- Buttons
- Modals
- Loader
- Icon
literally anything we find ourselves reusing often in our application.
How to Register components globally
Let us see two ways this can be done.
If we have a component let's call it BaseButton
and we want to use this button component in different locations in our app, we can go to our main.js
file and import the icon. Then register the component in our main.js file using Vue's Vue.component()
method.
import vue from 'vue'
import App from './App.vue'
import BaseButton from '@/components/BaseButton.vue'
Vue.component('BaseButton', BaseButton)
new Vue({
render: h => h(App)
}).$mount("#app");
The first argument passed into the Vue.component()
is the name we want to call the component and the second argument is the BaseButton component from the import statement from above.
Note:Make sure the component is registered before the vue instance below it.
Now you can use your component anywhere in your app without importing it to the component you want to use it in.
But if you are building a large application, and you have like 10-20 components you want to be global, this method for global registration might not be the best. In this situation, we can use automatic global registration
Automatic Global Registration.
In the official Vue documentation , this way of registering component is shown. The main solution code to automatically register components looks like this:
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
const requireComponent = require.context(
'./components',
false,
/Base[A-Z]\w+\.(vue|js)$/
)
requireComponent.keys().forEach(fileName => {
const componentConfig = requireComponent(fileName)
// Get PascalCase name of component
const componentName = upperFirst(
camelCase(
fileName
.split('/')
.pop()
.replace(/\.\w+$/, '')
)
)
Vue.component(
componentName,
componentConfig.default || componentConfig
)
})
The above block of code should be put in your main.js file and remember all global registration should be done before the root vue instance. Let me explain step by step what each block of code does.
Before using automatic global registration you have to install lodash first.
npm install lodash
or
yarn add lodash
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
Above the upperFirst
and camelCase
method are imported from the lodash library. The upperFirst
method converts the first letter of any string to capital letters while the camelCase
method converts a string either separated by -
, __
or --
to camelCase.
const requireComponent = require.context(
'./components',
false,
/Base[A-Z]\w+\.(vue|js)$/
)
This second block of code first initializes a variable requireComponent
and sets it equal to require.context
which is a webpack function method that matches files and used to automate the import of modules, so that you don't need to import a component every time you need to use it somewhere in your app. This require.context
method accepts 3 arguments as we see in our code block above.
- The first argument is the relative path to the components we would like to be automatically registered globally which is
./components
as you can see in your folder structure. - The second argument is a boolean.
true
meaning to check subfolders in our./components
folder andfalse
not to check any subfolders. - Three is a regular expression, don't worry if you aren't familiar with regular expression. All the expression does is searches for filenames that start with
Base
and ends with.vue
After accepting the three arguments, it returns an array of All the filenames that match the regular expression.
requireComponent.keys().forEach(fileName => {
const componentConfig = requireComponent(fileName)
const componentName = upperFirst(
camelCase(
fileName
.split('/')
.pop()
.replace(/\.\w+$/, '')
)
)
Above for each file name in requireComponent
array, we use the upperFirst
and camelCase
method to turn each filename to camelcase and the first letter to uppercase. Then .split
,.pop
, and .replace
searches for the file name that matches regardless of folder depth.
we then register our component globally
Vue.component(
componentName,
// Look for the component options on `.default`, which will
// exist if the component was exported with `export default`,
// otherwise fall back to module's root.
componentConfig.default || componentConfig
)
})
Now you can create Base components like BaseIcon
, BaseButton
, BaseInput
in your app and use them anywhere without importing them.
Conclusion
keep in mind that any component made global is made available in all components whether you need them or not. This might increase javascript bundle size.
If this tutorial has helped you, tell me below in the comments.