Last active
July 12, 2020 16:40
-
-
Save NicolasDurant/048e33bafdc81766a0d30222763594d3 to your computer and use it in GitHub Desktop.
[Nuxt - BaseComponents Globally Register Plugin] Plugin Script for the Nuxt.js Framework that goes through every file in the src/components/base folder and registers the components with Base+ComponentName globally, so you can access them anywhere in the code without the need of importing them. #NuxtJS #JavaScript #VueJS #NuxtConfig
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Has to be in the Nuxt plugins/ folder | |
import Vue from 'vue' | |
import upperFirst from 'lodash/upperFirst' | |
import camelCase from 'lodash/camelCase' | |
const requireComponent = require.context( | |
// The relative path of the components folder | |
'@/components/base', | |
// Whether or not to look in subfolders | |
false, | |
// The regular expression used to match base component filenames | |
/[A-Z]\w+\.(vue|js)$/ | |
) | |
requireComponent.keys().forEach((fileName) => { | |
// Get component config | |
const componentConfig = requireComponent(fileName) | |
// Get PascalCase name of component | |
const componentName = | |
'Base' + | |
upperFirst( | |
camelCase( | |
// Gets the file name regardless of folder depth | |
fileName | |
.split('/') | |
.pop() | |
.replace(/\.\w+$/, '') | |
) | |
) | |
// Register 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 | |
) | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
plugins: [ | |
{ mode: 'client', src: '~/plugins/base' } | |
], |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment