A guide on setting up Webpack to directly load a module from its source folder rather than the distribution folder

Currently, I am involved in a monorepo project and I need Webpack to fetch my source files from the src directory instead of the dist folder (as specified in the package.json file).

Let's consider the structure below:

/packages/core/dist/index.js (compiled output)
/packages/core/src/index.ts (original TypeScript source)
/packages/core/package.json (`main` and `module` point to `dist`)

Now, within the /packages/foo/src/index.ts file, I have an import statement like import Foo from '@test/core'. The issue arises when Webpack reads the core package's package.json because it uses the module and main fields pointing to the dist folder. In this case, I need Webpack to load the original sources from the src directory as @test/core is part of my internal codebase and not an external library.

My question is: Is there a method to instruct Webpack to exclusively load the original TypeScript sources for specific modules that start with @test/?

Answer №1

To simplify your file paths, you can implement a resolve alias in your webpack configuration.

For instance, if your webpack config is located above the packages folder, you can do the following:

{
  resolve: {
    extensions: [".ts", ".js", ".json"],
    alias: {
      "@test/core": path.resolve(__dirname, "packages/core/src")
    }
  }
}

Now, whenever you use require with paths starting with @test/core, they will be resolved to

path.resolve(__dirname, "packages/core/dist")
.

  • require("@test/core") => packages/core/src/index.ts
  • require("@test/core/module") => packages/core/src/module.ts

Since .ts is not a standard extension, make sure to include it in resolve.extensions.

Answer №2

I managed to fix this issue using the NormalModuleReplacementPlugin:

Here's what I added to my Webpack configuration:

 plugins: [
    new webpack.NormalModuleReplacementPlugin(
      /@test\/[a-z]+$/,
      resource => {
        resource.request = resource.request + '/src/index'
      }
    )
 ]

Since I'm working with TypeScript, I also made sure to include the .ts extension in:

resolve: {
  extensions: ['.ts', '.tsx', '.js', '.jsx']
}

Now when I import @test/xyz, it will be treated as @test/xyz/src/index -- and TypeScript files (.ts) will take precedence.

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

WebStorm highlights user-defined Jasmine matchers as mistakes and displays `TypeScript error TS2339: Property 'matcher' does not exist on type 'ArrayLikeMatchers '`

I am currently working on testing a hybrid Angular and Angular.js app using Karma / Jasmine. The previous code utilized custom matchers which worked flawlessly, and these same matchers are being used in the new TypeScript code. Strangely, although the Type ...

When parameters are added to one route, all other routes cease to function properly

After I added a parameter to one of the routes, all the other routes stopped rendering correctly (i.e., router-view is not working at all). The route /download/:id works as expected. Am I missing something in the setup? I tried leaving and removing the /do ...

Using Pocketbase OAuth in SvelteKit is not currently supported

I've experimented with various strategies, but I still couldn't make it work. Here's the recommendation from Pocketbase (): loginWithGoogle: async ({ locals }: { locals: App.Locals }) => { await locals.pb.collection('users' ...

Step-by-step guide on incorporating an external library into Microsoft's Power BI developer tools and exporting it in PBIVIZ format

I'm attempting to create a unique visualization in PowerBI using pykcharts.js, but I'm running into issues importing my pykcharts.js file into the developer tool's console. I've tried including a CDN path like this: /// <reference p ...

How can I embed an iframe in an Angular 4 application?

I'm facing an issue with my Angular 2 v4 application where I have the following code snippet: <iframe src="https://www.w3schools.com" style="width: 100%; height: 500px"></iframe> However, the iframe does not seem to work. I attempted to ...

Issue with using react-signature-canvas inside an ant design Modal

Encountering a problem with SignaturePad within the ant design component library's "Modal" component, as it fails to generate the base64 image. Upon reaching the trim function in the signaturepad code, the output is "data:". However, without the Moda ...

Exploring the process of selecting checkboxes in Angular 6

I'm currently learning Angular 6 and I have a requirement to mark checkboxes based on specific IDs from two arrays: this.skillArray = [ {ID: 1, name: "Diving"}, {ID: 2, name: "Firefighting"}, {ID: 3, name: "Treatment"}, ...

Error: Code cannot be executed because the variable "sel" has not been defined in the HTML element

Every time I try to click on the div, I encounter an error message stating 'Uncaught ReferenceError: sel is not defined at HTMLDivElement.onclick' I am currently developing with Angular 8 and this error keeps popping up. I have read through simil ...

I am encountering problems with images that are imported as module imports in a Vue.js project

Currently, I have stored all the default images for my Vue project in a designated folder. The path to this folder is web/images/defaults/<imageNames>.png. Instead of importing each image individually in my components, I wish to create a file that co ...

Exploring ways to access elements within shadow-root (open) in Angular using SVG.js

I'm currently tackling a project involving Angular Elements. Within this specialized component, my goal is to incorporate SVG.js 3+. However, due to the necessity of utilizing ViewEncapsulation.ShadowDom in my component, I am encountering challenges w ...

Filtering the data in the table was successful, but upon searching again, nothing was found. [Using Angular, Pagination, and

Having a table with pagination, I created a function that filters the object and displays the result in the table. The issue arises when I perform a new search. The data from the initial search gets removed and cannot be found in subsequent searches. Bel ...

Tips for extracting data from an Angular object using the *ngFor directive

https://i.stack.imgur.com/ai7g1.png The JSON structure displayed in the image above is what I am working with. My goal is to extract the value associated with the key name. This is the approach I have taken so far: <span *ngFor="let outlet of pr ...

Transforming TypeScript: converting to a comparable type

In my project using TS to develop a node express API, I have implemented separate modeland viewmodel classes. A Post model class can have multiple viewmodel representations. The question is, how can I convert from a model to a viewmodel class? One solutio ...

Tips on setting up Storybook.js with Next.js, utilizing Ant Design, Less, and TypeScript

I've been attempting to set up Storybook with Next.js, Ant Design, Less, and TypeScript. Despite following multiple tutorials, I haven't had any success. Below are my configurations and the error message I'm encountering... Here is what my ...

Angular 5: ngModelChange not triggering API call on bad request

When a user inputs a city name in a text box, I need to check if it is valid by calling the onCityChange() function using ngModelChange. This function emits the user-entered data on an rxjs Subject, which I subscribe to in the ngOnInit() method. Utilizing ...

How can Firebase and Ionic be used to customize the password reset template for sending verification emails and more?

I'm facing an issue with firebase's auth templates not supporting my native language. Is there a way to customize the password reset template to also handle verification and email address change emails? ...

Angular obtains an undefined response from a service

Having trouble retrieving the data from my service. Working with Angular 8. Here's the code snippet: Within the service: query(url: string) { this.subscription = this.socket$.subscribe( (message) => { return message; }, ...

Working with Array of Objects Within Another Array in Angular 6 Using Typescript

I'm currently working with an array of "food": "food": [ { "id": 11, "name": "Kabeljaufilet", "preis": 3.55, "art": "mit Fisch" }, { "id": 12, "name": "Spaghetti Bolognese", "preis": 3.85, "art": "mit Fleisch" }, { "id": 1 ...

What is the method for designating a precise subtype within an interface?

I am facing an issue with my Carousel. It is supposed to render a card with data if available, or a skeleton when there is no data. The error I am encountering is: Type 'EmptyElement' is not assignable to type 'Annonce | Annonce2'. Ty ...

Is it possible to export all types/interfaces from .d.ts files within multiple folders using index.ts in a React TypeScript project?

In my current React project, I am managing multiple configuration folders: -config -api/ |index.ts |types.d.ts -routes/ |index.ts |types.d.ts ... For example, in the api/index.ts file, I can import necessary types using import {SomeTyp ...