[Vuejs]-Auto Import Components Inside A Component In Vue JS

0👍

Auto Import all components from src/components directory that start with "Base" e.g. BaseInput.vue, BaseSelect.vue etc. (Project Created Using Vue CLI)

src/views/EventCreate.vue

<template>
    //template data here
</template>
<script>
    import upperFirst from "lodash/upperFirst";
    import camelCase from "lodash/camelCase";

    //require.context function from webpack
    const requireComponents = require.context(
      "../components",
      false,
      /Base[A-Z]\w+\.(vue|js)$/
    );

    let comps = {};

    requireComponents.keys().forEach((fileName) => {

      //removing extension converting to valid component name e.g. "./base-input.vue" to "BaseInput"

      const componentConfig = requireComponents(fileName);
      const componentName = upperFirst(
        camelCase(fileName.replace(/^\.\/(.*)\.\w+$/, "$1"))
      );

      //add it to comps object with dynamic name
      comps[componentName] = componentConfig.default || componentConfig;
    });

    export default{
        components:{ ...comps }
        //remaining exports here
    }
</script>

<style scoped>
   //style here
</style>

Leave a comment