Exporting all components using require: A complete guide

Currently, I am working on a Vue js application where I am tasked with exporting all the files and components from a specific directory. These files/components need to be imported into a separate file named paths.js.

If I use the require function to import all the components in index.js, how can I correctly export them so that they can be accessed in path.js as

import {Component1, Component2} from index.js
?

Please note: I do not want to manually include each component in index.js using the import keyword, which is why I am utilizing require.

Index.js

import upperFirst from "lodash/upperFirst";
import camelCase from "lodash/camelCase";


const requireComponent = require.context(".", true, /\.vue$/); // fetches Component1.vue and Component2.vue
const components = {};


requireComponent.keys().forEach(fileName => {
  const componentConfig = requireComponent(fileName);
  const componentName = upperFirst(
    camelCase(fileName.replace(/^\.\//, "").replace(/\.\w+$/, ""))
    );
  
  components[componentName] = requireComponent(fileName).default;
  
});
export default components;

paths.js

import {Component1, Component2} from 'index.js';'

console.log(Component1); // undefined

I have attempted to export components using export {...components}, but that resulted in an error.

Answer №1

The correct way is to

import Component from 'index.js'

You have exported it as a single constant value.

Answer №2

There are no references to ComponentX or ComponentY in Index.js, however, I believe I understand what you're trying to achieve.

You can accomplish this using Named exports and imports.

Here's a straightforward example:

index.js

export {components[0] as ComponentX};
export {components[1] as ComponentY};

export default components;

paths.js

import {ComponentX, ComponentY} from 'index.js';
//some code

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The tab indicator in Material-UI fails to update when the back button is clicked

My code is currently functioning well: The tab indicator moves according to the URL of my tab. However, there is a peculiar issue that arises when the back button of the browser is pressed - the URL changes but the indicator remains on the same tab as befo ...

Issue encountered while implementing search functionality with pagination in Laravel using Vue.js and Inertia

Recently, I have embarked on my journey to learn Laravel 8 along with vuejs and inertiajs. My current challenge involves creating a pagination search table. Despite diligently following tutorials, I keep encountering errors. Below is the code snippet for ...

ngClass binding fails to update when using directives to communicate

I am looking to combine two directives in a nested structure. The 'inner directive' includes an ng-class attribute that is bound to a function taking parameters from both inner and outer scopes, and returning a Boolean value. This is the HTML co ...

What is the process of creating a download link for a server file in a web browser?

I am attempting to create a straightforward download link for a PDF file that users can upload and then have the option to download. I would like this download feature to appear either in a pop-up box or simply on the Chrome download bar. Despite trying v ...

Got a not-a-number (NaN) value for the `children` prop in a

Just starting out with React and working on a type racer app. I've encountered an issue while trying to calculate WPM (Words per minute) - the calculation keeps returning 'NaN'. I've double-checked all the variables and ensured there ar ...

Best method for reverting react-native to previous version

Here's the dilemma I'm facing: I had a functional version of a react-native project that was running smoothly and committed to my git repository. Deciding to upgrade from react-native 0.26.3 to 0.28 led me into a tangled web of dependencies, so ...

How can I access a PHP variable from an external .php file within a JavaScript script?

I have recently implemented a JavaScript code called "upload.js" for uploading files to my server: function beginUpload(){ document.getElementById('upload_form').style.visibility = 'hidden'; return true; } function endUpload(s ...

The AJAX call is not being identified correctly

I am facing an issue with my search result pagination wherein the page reloads instead of loading via AJAX when using the pagination. The search results are correctly loaded through partial view with AJAX, but the pagination triggers a non-ajax request cau ...

Typescript and Mongoose Schema - Common Design Mistakes

I am encountering two issues while defining a schema using mongoose and typescript. Below is the code snippet I'm having trouble with: import { Document, Schema, Model, model} from "mongoose"; export interface IApplication { id: number; name ...

Creating interactive buttons with CSS and jQuery

As a newcomer to coding, I'm trying my hand at creating two buttons that transition from green to blue with a single click, and eventually incorporating them into a live website. The functionality I'm aiming for includes: Both buttons startin ...

webstorm error: unresolved function or method when using npm azure-storage modules

Encountering a problem with WebStorm IDE when using azure-storage library as it is unable to find the correct methods for intelligent coding (although the code runs without errors). View image of unresolved function or method Appreciate any help you can ...

Why isn't the customer's name a part of the CFCustomerDetails class?

Currently, I am utilizing the cashfree-pg-sdk-nodejs SDK to integrate Cashfree payment gateway into my application. Upon examining their source code, I noticed that the CFCustomerDetails class does not include the customerName attribute. https://i.stack.i ...

Currently, I am creating a regular expression to manage a specific task, but I have hit a roadblock in

Criteria: The string must not contain any uppercase letters. Special characters such as '^$.?*+()' are not allowed in the string. If the string includes '[', it must be followed by zero or more characters other than '[' and & ...

What is the best way to position the button under the label?

I attempted to place the 'search' button underneath the 'branch' label, below is the code snippet I used <template> <base-header class="pb-4 pb-5 pt-6 pt-md-6 bg-gradient-success"> <template> <div> ...

Implementing CORS in ReactJs: A Step-by-Step Guide

When working with React.js, I often use this fetchData config: fetchData = () => { fetch("http://localhost:8000/batch_predict", { method: "POST", headers: { 'Accept': 'application/json, text/plain, */*&apo ...

Contrasting the purpose of a function in pure JavaScript versus a function within the scope of an Angular controller

Could someone clarify the distinction between declaring these two functions in an angular controller? function demo() { }; scope.demo = function() { }; Are these two functions similar in perf ...

JQuery requests functioning flawlessly on one system while encountering issues on other systems

I've encountered an issue with the code on my admin page. It used to work perfectly fine on my system, but now it seems to have stopped functioning. My client urgently needs to update this page, however, when I attempt to run it, the JQuery requests a ...

Guide on converting a unique JSON structure into a JavaScript object

I've been on the hunt for a solution to this unique format challenge, but have hit a dead end so far. The issue at hand is that I'm dealing with a JSON format that doesn't play nicely with mongoDB. My goal is to convert the JSON data into a ...

Is AngularJS treating variables as text in their dynamic template directives?

Need help modifying this Angular component: (more details here: https://github.com/khan4019/tree-grid-directive) The issue at hand is simple. The tree-grid component does not allow formatting of specific columns using filters. For example, I want to conv ...

"Execute asynchronous tasks in Javascript and receive the returned

Currently, I am utilizing JSF ajax within my application and unfortunately, we are unable to make any changes to that. In the process of waiting for user action, I find it necessary to prompt the user before executing the ajax method. Specifically, I need ...