The order of resolution for Webpack dependencies in index.ts is incorrect

In our latest project, moduleResolution: 'node' plays a crucial role. We utilized index.ts barrels to streamline the import statements. However, during the app build process with webpack, it appears that the modules are being resolved in an incorrect order:

For instance, we have a file named iconSet.ts

export var IconSet = {
    Add: 'icon-add',
    Remove: 'icon-remove'
}

Then, there is another file called icons.ts, which imports the IconSet variable

import { IconSet } from '.'

export var Icons = {
    Add: IconSet.Add,
    Remove: IconSet.Remove
}

Lastly, there is an index.ts file that consolidates all exports like so:

export * from './icons'
export * from './iconSet'

The issue arises when importing the Icons variable in app.ts, as icons.ts gets processed before iconSet.ts:

import { Icons } from '.'
console.log(Icons); // <- Cannot read property 'Add' of undefined

It was expected that webpack would handle this problem seamlessly.

To replicate the problem, a minimal repository has been created: https://github.com/eulbot/webpack-es6-index-barrels

Answer №1

We encountered a similar issue in our own projects. To resolve it, we decided to rearrange the order of export lines like this:


export * from './iconSet'
export * from './icons'

This adjustment seemed to do the trick.

It appears that when ClassA imports ClassB, the index.d.ts file should have ClassB listed before ClassA.

Furthermore, you may want to consider having classes import each other directly rather than through the index.d.ts file. We discovered that importing classes directly from their respective files (for example, importing IconSet from iconSet.ts) allows Webpack + ts-loader to properly handle dependencies.

Answer №2

After testing on Node 9.3.0 with MacOs, it seems that the sample repository you shared is functioning correctly.

The result is:

{ Add: 'icon-add', Remove: 'icon-remove' }

I experimented with both development and production modes using webpack cli. Specifically, I used

node_modules/.bin/webpack-cli --mode=development
.

Currently, I am facing a similar issue which I suspect might be due to circular references, referencing an old problem discussed in this previous thread.

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

Webpack loaders or plugins: understanding the distinction

Can you explain the distinction between loaders and plugins in webpack? I found on the documentation for plugins that it states: Plugins are used to incorporate extra functionalities usually related to bundles within webpack. While I understand that b ...

Leveraging Java and TypeScript code for specific functionalities within an Ionic 2 Android application

When it comes to creating hybrid apps that support Windows, iOS, and Android simultaneously using web technologies such as Html, CSS, and Js, Ionic is the go-to choice. However, there may be certain features not supported by the Ionic 2 framework. Is it ...

Tips for transferring variables between two browser windows within the same session of Internet Explorer 11

Is there a way to prevent a parameter from displaying in the address bar and avoid storing it locally? For example, the parameter value is like vndfj/dfgdgdfg12/dg==. I attempted the following code, but it does not work on IE and Edge browsers: let data ...

Mismatched URLSearchParam type {property: value} does not match with undefined and Argument Type {property: value} cannot be assigned to {property: value}

Every time I try to run the code below, I encounter this error. The code is supposed to take a refresh token as input and make a POST request using URLSearchParams to a specific URL. However, I keep getting an error related to URLSearchParams. https://i.s ...

Utilizing MathJax in the AstroJS project to convert all [tex] code on the page into MathML code when building

In my latest project, I've implemented AstroJS as a Static Site Generator. One of the key benefits of utilizing AstroJS is its capacity to execute JS code within the --- --- code fences section of a .astro file, enabling the creation of webpages witho ...

Issue with Typescript: React Native useRef indicating potential null object error

I am encountering an issue with using a ref on a View in React Native. TypeScript is throwing the error "Object is possibly 'null'". What is the correct way to type a ref used on a View? I am specifically working with an Animated.View, although i ...

What would happen if I eliminated the preset test cases from a large-scale Angular project?

Currently, in my Angular 5 enterprise application, I have developed numerous components and services using the Angular CLI. Each of these components and services has spec files with the default test case 'Component/Service should be created'. Co ...

Leveraging NextModuleFederation for advanced dynamic routing through remote application integration

I recently started using the next-module-federation for a project at my company. Our aim is to develop 6-7 separate apps, each with its own route. For instance: AppRemote1 - ./src/pages/index.jsx ----> /remote1 AppRemote2 - ./src/pages/index.jsx ----> ...

Can TypeScript convert JavaScript files automatically using a compiler?

Is there a way to use TypeScript files like this? <script type="text/typescript"> // ... </script> I came across https://www.typescriptlang.org/play/index.html, which can compile TypeScript. What compiler does this website use? I tried ...

Adjusting the angular routerLink based on an observable

When working with HTML in Angular, I am looking for a way to use an <a> tag that adjusts its routerlink based on whether or not a user is logged in. Is it possible to achieve this functionality within a single tag? <a *ngIf="!(accountService ...

Tips for obtaining the ID and value for every Slide-Toggle element

I recently posed a question that was somewhat similar to this, but I am facing a slightly different issue now. Within a table column, there are Slide-Toggle elements that users can toggle between true and false an unlimited number of times. Following these ...

Error: *** is not a valid function within a React element

I am encountering an issue while attempting to call a function of an object passed as an argument in a React component's constructor. The error message I receive is: Uncaught TypeError: _this.layout.getWbsLayout is not a function at new Wbs (Wbs. ...

Passing a boolean as the value for a Material UI MenuItem in a React TypeScript application

I am encountering an issue as a beginner in react with passing a simple boolean value as a prop for the MenuItem component in the material UI library. I believe the solution is not too complex. Can someone provide guidance on how to fix this error? The sp ...

Is it possible to reorganize the JavaScript modules created by the TypeScript compiler?

In my TypeScript project, the structure resembles that of a typical Maven Java project. Here is an overview of how the project is organized: *.js file for commonjs/webpack, system, and amd.</p> For commonjs/webpack, I utilize tsc with tsconfig.jso ...

Encountering an issue while trying to import the validator module in NextJS 13

I encountered a peculiar issue while trying to import a module. Nextjs presented the following error message: ./application/sign_in/sign_in_store.ts:2:0 Module not found: Can't resolve 'validator' 1 | import { createEvent, createStore } fr ...

How is it possible that TypeScript does not provide a warning when a function is called with a different number of arguments than what is expected?

I am working on a vanilla JavaScript project in VS Code and have set up jsconfig.json. Here is an example of the code I am using: /** * @param {(arg: string) => void} nestedFunction */ function myFunction(nestedFunction) { // Some logic here } myFu ...

Seems like Visual Studio Code Intelisense is mistakenly flagging errors when utilizing the sequelize get method with Typescript

I am working with a Sequelize model that looks like this: export class Opportunity extends Model { @IsUUID(4) @PrimaryKey @Column({ type: DataType.UUID, }) opportunityId: string; @ForeignKey(() => AccountContact) @Column({ type: D ...

Attempting to implement dynamic selectors in my functions to avoid redundancy

Here is some code I find myself writing frequently for parsing JSON or creating functions. // Reusable adder functions async function addImagesToEntity(entityId, fileName, entity) { const entity = await db.${entity}.findById(entityId); await entity.${e ...

Ensuring equality of values in Angular2 reactive forms

I'm currently working on an Angular2 Reactive form that requires users to confirm their email address. You can check out the plunker for reference here import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Vali ...

What is the best way to utilize the constructor in a JavaScript object so that only the properties within `this` are utilized?

I am looking to instantiate the following class: class Person { firstName; lastName; birthday; constructor(props: Person) { {firstName, lastName, birthday} = props } } var me = new Person({firstName: "donald", lastName: "trum ...