What is the best way to utilize the ts-loader configFile option?

Including the ./package.json in my webpack.config.ts was straightforward, but to make it work, I had to utilize the

"resolveJsonModule" : true
option in my ts-config-file.

Everything worked perfectly when I placed the tsconfig.json file at the same level as webpack.config.ts.

--
  |
   - tsconfig.json
   - package.json
   - webpack.json

The npm script looked like this:

"webpack": "webpack -c webpack.config.ts --stats=errors-warnings"
.

However, things took a bad turn when I decided to rename tsconfig.json or add another file named tsconfig.dev.json. This caused the webpack build to fail:

> webpack -c webpack.config.ts --stats=errors-warnings

[webpack-cli] Failed to load '/path/to/frontend-shared/webpack.config.ts' config
[webpack-cli] webpack.config.ts:5:25 - error TS2732: Cannot find module './package.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.

5 import packageJson from './package.json';

I attempted to guide webpack on how to locate this configuration file:

loader: 'ts-loader',
options: {
    configFile: './tsconfig.dev.json'
}

The complete webpack configuration looks like this:

const config: webpack.Configuration = {
    context: path.resolve(__dirname),
    mode: 'production',
    entry: {
        sdpFrontend: {
            import: path.join(__dirname, 'index.tsx',),
            dependOn: ["framework"]
          },
        framework: ['react']
    },
    module: {
      rules: [
        {
            test: /\.(ts|js)x?$/,
            exclude: /node_modules/,
            use: [
                {
                    loader: 'ts-loader',
                    options: {
                        configFile: './tsconfig.dev.json'
                    }
                }
            ]
            // ,
            // options: {
            //     configFile: "tsconfig.dev.json"
            // }
        }
      ],
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js"],
        modules: [path.resolve(__dirname, 'src'), 'node_modules']
    },
    output: {
        path: path.resolve(__dirname, "js"),
        filename: "[name]-[contenthash].js",
        clean: true
    },
    optimization: {
        // splitChunks: {
        //     chunks: 'all'
        // },
        // https://webpack.js.org/configuration/optimization/#optimizationruntimechunk
        runtimeChunk: 'single',
        minimize: false
    },
    plugins: [

        new HtmlWebpackPlugin({
            // https://github.com/jantimon/html-webpack-plugin#options
            inject: false,
            template: "./index.tmpl.html",
            filename: "../index.html",
            appVersion: packageJson.version
        }),
    ]
};

What could be going wrong here? Could it be that ts-loader is simply ignoring this option?

Just for clarification, here are some versions being used:

"devDependencies": {
    "@types/webpack": "^5.28.0",
    "html-webpack-plugin": "^5.5.0",
    "npm-run-all": "^4.1.5",
    "ts-loader": "^9.2.6",
    "ts-node": "^10.4.0",
    "typescript": "^4.5.4",
    "webpack": "^5.67.0",
    "webpack-cli": "^4.9.2"
  }

Answer №1

Give this setup a shot

module: {
        rules: [
            {
                test: /\.ts?$/,
                exclude: /node_modules/,
                loader: "ts-loader",
                options: {
                    configFile: "[your-ts-config-path]",
                }
            }
        ]
    },

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

Using NPM packages within the process environment

Can you explain how all these packages are installed in process.env? Also, why is NODE_ENV not visible when I run npm scripts? "start": "NODE_ENV=dev npm run build && npm run watch && npm run tslint" https://i.sstatic.net/OpahA.png Here ...

The compilation of the Angular application is successful, however, errors are arising stating that the property does not exist with the 'ng build --prod' command

When compiling the Angular app, it is successful but encountered errors in 'ng build --prod' ERROR in src\app\header\header.component.html(31,124): : Property 'searchText' does not exist on type 'HeaderComponent&apo ...

Transforming an Established React Project into a Progressive Web Application

Currently, I have an existing react tsx project that has been set up. My goal is to transform it into a PWA by adding service workers. However, after adding the service workers in the src folder, I encountered an error when attempting to deploy on firebase ...

Ensuring seamless collaboration between Typescript node modules

Is there anyone who has successfully set up a configuration where module 1, using TypeScript, is referencing another module 2 also with TypeScript, and both are utilizing tsd types like node.d.ts? I have been able to compile and use both modules without a ...

FlatList: Can you list out the attributes of ListRenderItemInfo<>?

I am attempting to utilize a FlatList in the following manner: <FlatList data={vehicles} horizontal={false} scrollEnabled renderItem={({ vehicle}) => <VehicleContainer vehicle={vehicle} />} ...

Converting JSON responses from Observables to Arrays of objects in Angular

I have created a custom interface called Table which defines the structure of my data. export interface Table { id: number; title: string; status: string; level: string; description: string; } In my service, I am using HttpClient to se ...

The React-bootstrap components lack predefined styles

I have been working on a web application using react.js, react-router, and webpack. I wanted to style it using react-bootstrap for the navbar, but it seems that my navbar is not getting styled properly as shown in the documentation here Here is the react- ...

Customizable return type for optional function parameter

Imagine this scenario with a factory function const createIndex = <PK extends string, SK extends string>(pk: PK, sk?: SK) => ({ pk, sk }); const i1 = createIndex("pk1"); // expected type of i1: { pk: "pk1" } const i2 = createIn ...

Utilizing Gulp to Convert TypeScript Exports into a JSON File

I have a set of TypeScript files, some of which export a specific variable - named APIS - which contains an array of objects. My goal is to extract the values from all of these exports and save them into a JSON file using Gulp. Let's consider a direc ...

Using RxJs in an Angular 2 application to enable row selection in a table by detecting mouse movements

Check out this example of an Angular 2 application with row selection in a table: https://plnkr.co/edit/HdQnWqbg9HloWb4eYGHz. The row selection functionality is implemented using mouse event handlers (mousedown, mousemove, mouseup). Below is the template ...

How can TypeScript leverage types to build values?

I am dealing with the code snippet provided below: type Chocolate = { 'flavour': 'Chocolate', 'calories': 120 } type Vanilla = { 'flavour': 'Vanilla', 'calories': 90 } type Mango = ...

Instructions for enabling the touch slider feature in the Igx carousel component with Angular 6 or higher

Looking to enable the touch slider for Igx carousel using angular 6+? I am trying to implement the igx carousel for image sliding with reference from a stackblitz demo (https://stackblitz.com/edit/github-j6q6ad?file=src%2Fapp%2Fcarousel%2Fcarousel.compone ...

Encountered an issue with resolving the module specifier while utilizing a Web Component

I recently added the @tokens-studio/configurator package from NPM to my project. However, upon importing it as instructed, I encountered the following error: Failed to resolve module specifier "@tokens-studio/configurator". Relative references m ...

Error with scoped slot typing in Vue3 using Vite and Typescript

I am currently working on a project using Vue3, Vite, and TypeScript as the devstack. I encountered an error related to v-slot that reads: Element implicitly has an 'any' type because expression of type '"default"' can't ...

Utilize external functions in evaluated code

After working with a TypeScript file containing the following code: import { functionTest } from './function_test' function runnerFunctionTest() { console.log("Test"); } export class Runner { run(source : string) { eva ...

What is the best way to handle optional parameters while also ensuring that a required parameter is passed in TypeScript?

Currently, I am working on a function that requires only one of the configurations specified in the SubNodeConfig interface. While I can set all of them as optional as shown below, I am looking for a way to make one of them mandatory, possibly using the no ...

Is it possible to modify the parameters of a function by utilizing a MethodDecorator without affecting the "this" value?

Consider a scenario where you need to dynamically modify method arguments using a decorator at runtime. To illustrate this concept, let's simplify it with an example: setting all arguments to "Hello World": export const SillyArguments = (): MethodDec ...

What is the role of authguard in securing routes?

When developing an application, I encountered the need to implement authorization to protect routes using AuthGuard. However, I now face the challenge of securing child routes based on a role system obtained from the backend during login. For example, if t ...

Trapped in the Google Maps labyrinth (Angular)

Hey there everyone! I'm currently working on an exciting angular application that integrates the Google Maps API. The goal is to create a feature that shows the 20 closest coffee shops based on the user's current location. However, I seem to be r ...

Tips for showcasing with [displayWith] in Material2's AutoComplete feature

My API returns an array and I am using Material2#AutoComplete to filter it. While it is working, I am facing an issue where I need to display a different property instead of the currently binded value in the option element. I understand that I need to uti ...