1
votes

I have a number of SVG cards as components in Vue; I probably have 50 or more. I could import them one by one just after the script tag:

<script>
import MyVueComponent1 from "~/components/MyVueComponent1.vue";
import MyVueComponent2 from "~/components/MyVueComponent2.vue";
import MyVueComponent3 from "~/components/MyVueComponent3.vue";
...
import MyVueComponent50 from "~/components/MyVueComponent50.vue";

But I've been reading that I can do this programmatically. I just haven't found any one example that makes it crystal clear to me. I able to register the components dynamically but I'm not certain how to import an entire folder of components.

I was able to register the components dynamically using this code in the created hook:

created() {
    const requireComponent = require.context(
      // Look for files in the current directory
      "../components",
      // Do not look in subdirectories
      false,
      // Only include "S" prefixed .vue files
      /S[\w-]+\.vue$/
    );

    // For each matching file name...
    requireComponent.keys().forEach((fileName) => {
      // Get the component config
      const componentConfig = requireComponent(fileName);
      // Get the PascalCase version of the component name
      fileName = fileName.replace("./", "");
      fileName = fileName.replace(".vue", "");
      const componentName = fileName;
      this.generatedComponentList.push(componentName);
      // Globally register the component
      Vue.component(componentName, componentConfig.default || componentConfig);
    });
  },

And I'm using the generatedComponentList of component names to display the cards:

<div
      v-for="componentName in generatedComponentList"
      :key="componentName"
    >
      <component :is="componentName" :id="componentName"></component>
    </div>

But I'd love to get rid of all the import lines under the script tag and have cleaner and more dynamic code. That way if I add a new component card to the folder, it will simply be "picked up" and displayed without having to add the "import" line, or register the component etc. Hopefully I've clearly articulated what I'm looking to achieve.

1
I do not understand your question - specifically the last paragraph. require.context does exactly what you want - just remove your static imports - Michal Levý
@kissu I do not think he is looking for dynamic components. It all looks to me pretty static in terms of runtime but dynamic at build time - more like auto-discover components at build + create a list of components to use at runtime - Michal Levý

1 Answers

0
votes

Nuxt auto-imports the components you use from the ~/components directory, so you don't need to import or register them explicitly.

This feature is enabled in nuxt.config.js with the components config:

// nuxt.config.js
export default {
  components: true
}