Webpack is having trouble bundling files while tsc is running

I am encountering some difficulties with webpack when trying to build my files. I keep getting a series of errors that all have the same format, such as:

ERROR in ./node_modules/typescript-rest/dist/server.js
Module not found: Error: Can't resolve 'typescript-ioc/es6' in '/Users/Jack/NODE/ts-rest-session/node_modules/typescript-rest/dist'

It appears that there is an issue with loading node_modules correctly.

tsc and ts-node are both able to successfully build/run the project. Below are my configurations:

tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "lib": ["es2015", "dom"],
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

webpack.config.js

module.exports = {
  entry: {
    server: './server.ts'
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    modules: ["node_modules"]
    extensions: ['.tsx', '.ts', '.js', '.json']
  },
  output: {
    filename: '[name].bundle.js',
    path: __dirname + 'dist'
  }
};

If anyone has any suggestions or ideas, please feel free to share! I have attempted removing node_modules from the exclude section of module.rules[0] in webpack.config.json but to no avail.

Answer №1

If you wish to handle module resolution based on baseUrl and paths specified in your tsconfig.json file, you can utilize the tsconfig-paths-webpack-plugin package. Refer to the module resolution documentation for more information on this functionality.

This particular feature is compatible with webpack version 2.1+ and TypeScript version 2.0+. Feel free to use the provided configuration or explore the package for detailed usage instructions.

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
...
    resolve: {
        plugins: [new TsconfigPathsPlugin({ /*configFile: "./path/to/tsconfig.json" */ })]
        }
...
}

https://github.com/TypeStrong/ts-loader/blob/master/README.md


MODIFY

It appears that your current setup aims at building a node application while webpack by default is optimized for web projects. Adjust the target in your webpack.config accordingly. Additionally, ensure proper syntax within the resolve section and set an appropriate output path like path: __dirname + '/dist'

I have tested and confirmed the compatibility of the following configuration for node applications:

var nodeExternals = require('webpack-node-externals');

module.exports = {
  mode: 'development',
  entry: './server.ts',
  // disregard built-in modules such as path, fs, etc.
  target: 'node', 
  // ignore all modules within node_modules folder
  externals: [nodeExternals()], 
  output: {
    filename: 'bundle.js',
    path: __dirname + '/dist'
  },

  // Enable sourcemaps for debugging webpack's output.
  devtool: 'source-map',

  resolve: {
    // Include '.ts' and '.tsx' in resolvable extensions.
    extensions: ['.ts', '.tsx', '.js', '.json']
  },

  module: {
    rules: [
      // All files with '.ts' or '.tsx' extension will be processed by 'awesome-typescript-loader'.
      {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader',
      },

      // Re-process any sourcemaps for resulting '.js' files using 'source-map-loader'.
      {
        enforce: 'pre',
        test: /\.js$/,
        loader: 'source-map-loader'
      },
    ]
  },
};

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

What methods are available for utilizing a runtime variable that TypeScript is unaware of?

I am looking to implement a global variable in TypeScript that will be defined dynamically at runtime. This global variable is necessary for transferring configuration properties from the server-side language to JavaScript. My approach involves using TypeS ...

One press sets off a chain reaction of unintended consequences

I am facing an issue where I want to implement functionality to modify the quantity of a selected product using two buttons: minus and plus. Strangely, when clicking the plus button it also triggers the click event of the minus button. Can anyone shed li ...

What is the best way to organize class usage within other classes to prevent circular dependencies?

The engine class presented below utilizes two renderer classes that extend a base renderer class: import {RendererOne} from "./renderer-one"; import {RendererTwo} from "./renderer-two"; export class Engine { coordinates: number; randomProperty: ...

Extract the event.data value from a window.addEventListener (MessageEvent) in order to trigger a separate function

Currently, I am delving into Angular and aiming to develop a LinkedIn Login API. To achieve this, I'm utilizing window.open to launch a new window where the user can either accept or decline the authorization. Upon successful acceptance, LinkedIn retu ...

Having trouble organizing data using matSort in conjunction with API information

Everything was running smoothly with my mat-table until I tried adding mat-sort as per the official API documentation. Unfortunately, it failed at ngAfterViewInit with the following error message: ERROR TypeError: Cannot set property 'sort' of u ...

Implementing a onClick event to change the color of individual icons in a group using Angular

I have integrated 6 icons into my Angular application. When a user clicks on an icon, I want the color of that specific icon to change from gray to red. Additionally, when another icon is clicked, the previously selected icon should revert back to gray whi ...

Error message: The function __classPrivateFieldGet(...) at is not defined

Encountered an error message stating: "Parsing error: __classPrivateFieldGet(...).at is not a function (eslint) error image here Parsing error: __classPrivateFieldGet(...).at is not a functioneslint Noticing errors in every first line of each tsx file. T ...

A problem occurred while compiling the 'SharedModule' template: The expression form is not compatible with the current system

In creating this share module, I have included the following components: @NgModule({ declarations: [ , DateToPersian , EnumToArrayPipe , SearchWtihInput , ConvertbytePipe , ArraySortPipe , MonySplitePipe , IsEllipsisActiveDir ...

Save a cookie within the Figma desktop application by utilizing the Node.js API

I'm currently developing a figma plugin using typescript that includes a login module. I've set up the API using Node.js, but I'm encountering an issue with storing cookies. After checking the console in the Figma desktop app, I noticed tha ...

Building a personalized Angular component to encapsulate an input field for use in reactive forms

I'm struggling to create a personalized component that includes an input form control. I'm unsure how to properly link the formControl directive and formControlName to the input element within my code. Here is what I have so far: <div class=" ...

Troubleshooting issues with Angular 8 component testing using karma leads to failure

As I begin testing my component, my first goal is to verify that the ngOnInit function correctly calls the required services. agreement.component.ts: constructor(private agreementService: AgreementService, private operatorService: Operato ...

Obtaining a phone number from a contact in Nativescript Angular: A step-by-step guide

Upon executing the following code: let desiredFields = ['display_name','phone','thumbnail','email','organization']; console.log('Loading contacts...'); let timer = new Date().getTime(); Contact ...

Redis Recursion: The callstack has reached its maximum size limit

Looking for some assistance with creating a game timer. I've decided to utilize Redis and Web Sockets in order to synchronize the timer across multiple devices. However, I'm running into an issue when trying to call my function recursively using ...

Tips for adding response buttons in BotFramework-Webchat for sending reactions to the Bot hosted on Azure

I am in the process of developing a chatbot using BotFramework-WebChat with Typescript and Azure for the backend. I am interested in adding reaction buttons (such as thumbs up, thumbs down) to each message in the chatbot, allowing users to interact with th ...

Guidelines for Managing Test Cases for a Promise-Returning Function with Resolve and Reject in Angular 6

I need to write a test case for a function that returns a Promise with resolve and reject. Here's the function definition: isAuthSuccess(): Promise<any> { const promise = new Promise((resolve, reject) => { if (this.userInfo) { ...

Is there a way to efficiently compare multiple arrays in Typescript and Angular?

I am faced with a scenario where I have 4 separate arrays and need to identify if any item appears in more than two of the arrays. If this is the case, I must delete the duplicate items from all arrays except one based on a specific property. let arrayA = ...

Angular5+ Error: Unable to retrieve summary for RouterOutlet directive due to illegal state

When attempting to build my Angular App using ng build --prod --aot, I consistently encounter the following error: ERROR in : Illegal state: Could not load the summary for directive RouterOutlet in C:/Path-To-Project/node_modules/@angular/Router/router.d. ...

ReactTS: Tips for organizing child components within a "container component"

Currently, I am in the process of developing reusable front-end components in React using Typescript. However, I am encountering a challenge related to a feature commonly found in traditional packages. My goal is to have the ability to nest children of a ...

Adapting inherited functions in typescript

I am looking to customize the error message in my RunTimeError class by overriding the asString function, as I need it to be different from the one in my generic Error class class Error { errorName: string; details: string; posStart: Position ...

Instead of using a `thisArg`, consider employing a closure when encountering problems with .pipe(map

The code I currently have is showing as deprecated. I am in need of assistance to update it, particularly the map section. There is an issue with the map part that needs attention. /** @deprecated Use a closure instead of a thisArg. Signatures accepting ...