|
| 1 | +# Automatic Global Registration of Base Components |
| 2 | + |
| 3 | +## Base Example |
| 4 | + |
| 5 | +Many of your components will be relatively generic, possibly only wrapping an element like an input or a button. We sometimes refer to these as [base components](../style-guide/#base-component-names-strongly-recommended) and they tend to be used very frequently across your components. |
| 6 | + |
| 7 | +The result is that many components may include long lists of base components: |
| 8 | + |
| 9 | +```js |
| 10 | +import BaseButton from './BaseButton.vue' |
| 11 | +import BaseIcon from './BaseIcon.vue' |
| 12 | +import BaseInput from './BaseInput.vue' |
| 13 | +export default { |
| 14 | + components: { |
| 15 | + BaseButton, |
| 16 | + BaseIcon, |
| 17 | + BaseInput |
| 18 | + } |
| 19 | +} |
| 20 | +``` |
| 21 | + |
| 22 | +Just to support relatively little markup in a template: |
| 23 | + |
| 24 | +```html |
| 25 | +<BaseInput v-model="searchText" @keydown.enter="search" /> |
| 26 | +<BaseButton @click="search"> |
| 27 | + <BaseIcon name="search" /> |
| 28 | +</BaseButton> |
| 29 | +``` |
| 30 | + |
| 31 | +Fortunately, if you're using webpack (or [Vue CLI](https://github.com/vuejs/vue-cli), which uses webpack internally), you can use `require.context` to globally register only these very common base components. Here's an example of the code you might use to globally import base components in your app's entry file (e.g. `src/main.js`): |
| 32 | + |
| 33 | +```js |
| 34 | +import { createApp } from 'vue' |
| 35 | +import upperFirst from 'lodash/upperFirst' |
| 36 | +import camelCase from 'lodash/camelCase' |
| 37 | +import App from './App.vue' |
| 38 | + |
| 39 | +const app = createApp(App) |
| 40 | + |
| 41 | +const requireComponent = require.context( |
| 42 | + // The relative path of the components folder |
| 43 | + './components', |
| 44 | + // Whether or not to look in subfolders |
| 45 | + false, |
| 46 | + // The regular expression used to match base component filenames |
| 47 | + /Base[A-Z]\w+\.(vue|js)$/ |
| 48 | +) |
| 49 | + |
| 50 | +requireComponent.keys().forEach(fileName => { |
| 51 | + // Get component config |
| 52 | + const componentConfig = requireComponent(fileName) |
| 53 | + |
| 54 | + // Get PascalCase name of component |
| 55 | + const componentName = upperFirst( |
| 56 | + camelCase( |
| 57 | + // Gets the file name regardless of folder depth |
| 58 | + fileName |
| 59 | + .split('/') |
| 60 | + .pop() |
| 61 | + .replace(/\.\w+$/, '') |
| 62 | + ) |
| 63 | + ) |
| 64 | + |
| 65 | + app.component( |
| 66 | + componentName, |
| 67 | + // Look for the component options on `.default`, which will |
| 68 | + // exist if the component was exported with `export default`, |
| 69 | + // otherwise fall back to module's root. |
| 70 | + componentConfig.default || componentConfig |
| 71 | + ) |
| 72 | +}) |
| 73 | + |
| 74 | +app.mount('#app') |
| 75 | +``` |
0 commit comments