Whenever I try to import a directory that contains modules, Webpack encounters an error

I am currently in the process of developing a small npm library to streamline API interaction. Here is an overview of my folder structure...

dist/
  index.js
src/
  index.js
  endpoints/
    endpoint1.js
package.json
webpack.config.js

Inside my src/index.js file, I have...

import {endpoint1} from './endpoints'

module.exports = class lib {
 ...
}

When running npm run build (which executes webpack --display-error-details --mode production), webpack throws a significant error stating "Module not found: Error: Can't resolve './endpoints' in 'my\project\dir\src'.

My current webpack.config.js file looks like this...

const path = require('path');

module.exports = {
    mode: 'production',
    entry: path.join(__dirname, '/src/index.js'),
    output: {
        path: path.resolve('dist'),
        filename: 'index.js',
        libraryTarget: 'commonjs2'
    },
    module: {
        rules: [
            {
                test: /.js?$/,
                exclude: /(node_modules)/,
                use: 'babel-loader'
            }
        ]
    },
    resolve: {
        modules: [

            path.resolve(__dirname, 'src/endpoints')
        ],
        extensions: ['.js']
    }
};

I've noticed similar questions asked in the past, and the suggested solutions haven't worked for me so far. I'm posting this in case I'm missing something obvious. Feel free to ask for more information if needed! Apologies for the lengthy text. Thank you.

Answer №1

The proper way to import the module is as follows:

 import endpoint1 from 'endpoint1';

By specifying the resolve.modules option in your Webpack configuration, you are instructing Webpack to search for modules in that specified folder when using non-relative paths. In this case, the module being imported is named "endpoint1".

It is important to note that this practice should be reserved for libraries that are utilized throughout your project. For a specific endpoint like this one, it would be more appropriate to use a relative import:

 import endpoint1 from "./endpoints/endpoint1";

Answer №2

When you see <code>import {endpoint1} from './endpoints'
, it essentially means that the code is importing something named enpoint1 from a file named ./endpoints/index.js. Just to clarify, when you import a directory, it specifically refers to the index.js file within that directory and not any other files present in it.

The names encapsulated within {} pertain to named imports and are applicable only for es6 modules-style imports such as import {...} from. If you do not include the {}, you are essentially importing the default export. On the flip side, CommonJs-style imports like const {...} = require('') function differently. CommonJS does not support named exports and imports; it simply imports the default from the file and then retrieves a specific field through object destructuring.

In the context of exporting, an unnamed (default) entity is exported from a file named ./endpoints/enpoint1.js. This 'unnamed' label arises due to the use of module.exports =, which aligns with the CommonJS-style export. In contrast, this would be equivalent to export default class lib ... in es6 modules-style exports.

If you need to import multiple files from a directory, consider the following solutions:

1) Often, single import points are introduced whereby you create an index.js file. Within this file, you manually import each desired file from the directory and subsequently export them under designated names. An example implementation could resemble the following:

import a from './a.js';
import b from './b.js';
import c from './c.js';

export { a, b, c };

By adopting this setup, you can successfully utilize the imports.

2) In certain uncommon scenarios, utilizing functions such as fs.readdir or fs.readdirSync to dynamically scan the entire directory and require files in a loop might prove beneficial. However, exercise caution and restrict its usage to imperative instances, such as for managing database migrations.

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

Ensure menu options are aligned to the right using material-ui

My material-ui menu currently has the following setup: <span> <Link to="/issues"> <Button style={isActive(history, "/issues")}>Issues </Button> </Link> <Link to="/users"> <Button style={isActive(his ...

Steps to deactivate a ladda button

I'm currently utilizing Ladda UI for bootstrap in my project. My goal is to disable a button using jQuery after the user clicks on it. Despite attempting to use ajax OnComplete / OnSuccess / OnBegin, I've had no luck - the button remains enable ...

How can I retrieve the input value on the current page using PHP?

Hey there, so I'm pretty new to PHP and I have a question. Is it possible to retrieve the input value from an existing input field on a page using PHP when the page loads, and then assign that value to a variable? For instance, let's say I have ...

The magic of data binding in AngularJS's ng-repeat

Is it possible to dynamically call an attribute of a data-binded object based on the ng-repeat object? I have set up a simple example, but I'm not sure if it can be solved this way. Can anyone help with this? The goal is for the input to receive the ...

Caller Function's Parents in JavaScript

I have functions in JavaScript that need to verify if they are being called by the correct function (for example, it requires the function something.stuff.morestuff.coolFunction to initiate it). I attempted using Function.caller, but it only gives me the f ...

Confirm that the method has been called by utilizing the AVA testing framework

As I work on creating a unit test for my React component using tools like Ava and Enzyme, I encounter an issue. My goal is to create a simple unit test that checks if a certain method has been called. The test should pass if the method has indeed been call ...

The presence of fsevents (imported by chokidar) in npm shrinkwrap leads to build errors on Windows operating system

On my Windows x64 environment, the fsevents library is causing issues during npm install. This problem stems from it being listed in the shrinkwrap due to its dependency on chokidar, which is only OSX compatible. Our Linux-based production environment is n ...

Transmitting a Wav file from JavaScript to Flask

I'm currently working on a JavaScript code that records audio from the browser and now I need to figure out how to send it back to Flask. start: function () { var options = {audio: true, video: false}; navigator.mediaDevices.getUserMedia(optio ...

Utilizing a custom keyboard with Jquery for a recurring function

It seems like I might be missing something simple here, as I am following the code tutorial provided in the link below: The goal of this project is to create a popup keyboard for a touch screen. Although I have made some modifications for specific purpose ...

bespoke filter designed to conceal any negative figures

I am trying to implement a feature where a text box will display nothing if the ng-model contains a negative value. I want the ng-model to remain unchanged while ensuring that negative values are not displayed. I am looking for a custom filter to achieve t ...

How to effectively handle a Lerna monorepo containing packages designed for both Vue 2 and Vue 3

I am currently working on creating a pull request to contribute to an open-source library that utilizes Lerna to manage multiple packages and npm as the package manager. Within the library, there is already support for Vue 2 through the existing package s ...

Leveraging AJAX for transferring variable from a dynamic HTML table to PHP for executing an update query

Is there a way to insert a value into the input field valor and update the respective row with that value using both the ID and the valor in the update query? I seem to be missing something here, what could it be? Table <?php $IDTipoEquipamento = ...

Having trouble accessing properties of an undefined object when trying to read 'credentials' in Firebase Auth within ReactJS

I need to verify the user's password again before allowing them to change it. Currently, my Firebase Auth setup is defined in Firebase.js and exported correctly //appConfig = ...(all the configurations here) const app = firebase.initializeApp(appConf ...

The communication between the Next.js and Node.js servers is being obstructed as the request body fails

Could you lend me a hand with this issue? Here is the function being called: function apiCreate(url, product) { console.log('Posting request API...' + JSON.stringify(product) ); fetch(url, { dataType: 'json', method: 'post ...

The save feature becomes dysfunctional after switching to the Material-UI dependency in a React project

After integrating the Material-UI dependency into my ReactJS code, I encountered an issue where the "save" functionality no longer works properly. Previously, when editing a task in my simple Todo list app, the new name would be saved successfully. However ...

Trying to filter out repetitive options in an autocomplete box

Using the jQuery autocomplete plugin, I am trying to display 5 unique search results. Initially, I achieved this by limiting the stored procedure to return only 5 results, but now I want to remove duplicates while still showing 5 distinct results. I'm ...

Is it possible to perform a forEach operation on two separate arrays simultaneously?

I have created two arrays and then utilized a function to assign values to certain variables based on the element clicked in the array. (Refer to the first code snippet) However, I am now looking to execute another function that makes use of these assigned ...

Switch the URL of the current tab to a different one by clicking a button within a Chrome extension with the help of JavaScript

Could someone assist me in changing the current tab URL to a different website, such as , using a chrome extension? Here is my JavaScript code: chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { var tab = tabs[0]; console.log(tab.url) ...

Attempting to create a redirection landing page

I have a process where I create a new user and save it in my database with the following code snippet: const newUser = new User({ username: userId, password: pass, nameOfUser: user_name, emailOfUser: user_email ); newUser.save(); res.redir ...

What is the best way to retrieve an object value within an if statement?

What can I do to ensure that the line within the if statement functions properly? const player1 = { name: "Ashley", color: "purple", isTurn: true, play: function() { if (this.isTrue) { return `this["name"] is current ...