When ts-loader is used to import .json files, the declaration files are outputted into a separate

I've encountered a peculiar issue with my ts-loader. When I import a *.json file from node_modules, the declaration files are being generated in a subfolder within dist/ instead of directly in the dist/ folder as expected.

Here is the structure of my project:

Project/
├── src/ 
│   ├── components/
│   │   └── PhoneNumberInput/
│   │       ├── index.ts
│   │       └── utils.ts
│   └── index.ts
├── package.json
├── tsconfig.json
└── webpack.config.js

When I run webpack (using the ts-loader), I anticipate the following output folder structure:

Project/
├── dist/ 
│   ├── components/
│   │   └── PhoneNumberInput/
│   │       ├── index.d.ts
│   │       └── utils.d.ts
│   ├── index.d.ts
│   └── index.js
└── ...

However, this setup changes when I start importing a .json file (from node_modules/) within my utils.ts:

import * as de from "react-phone-number-input/locale/de.json";

The declaration files are now created under dist/src/:

Project/
├── dist/ 
│   ├── src/
│   │   ├── components/
│   │   │   └── PhoneNumberInput/
│   │   │       ├── index.d.ts
│   │   │       └── utils.d.ts
│   │   └── index.d.ts
│   └── index.js
└── ...

As a result, any relative imports to assets are now broken. If I switch to using the awesome-typescript-loader or import a .json file from the project itself like this:

import * as de from "./countries.json";

The src/ subfolder does not appear.

Any insights on what might be causing this behavior? Am I overlooking something? Or could it potentially be a bug in the ts-loader? The example project can be accessed at https://github.com/psalchow/ts-path-test

For reference, here are the relevant configuration files:

package.json

{
  "name": "ts-path-test",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "build": "webpack --progress --mode=production"
  },
  "dependencies": {
    "react-phone-number-input": "^3.1.19"
  },
  "devDependencies": {
    "@types/react-phone-number-input": "^3.0.6",
    "@types/webpack": "^5.28.0",
    "awesome-typescript-loader": "^5.2.1",
    "ts-loader": "^8.1.0",
    "typescript": "^4.2.4",
    "webpack": "^4.46.0",
    "webpack-cli": "^4.6.0"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "allowJs": false,
    "baseUrl": "src",
    "declaration": true,
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "outDir": "dist",
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "strict": true,
    "suppressImplicitAnyIndexErrors": true,
    "target": "es2019"
  },
  "files": ["src/index.ts"]
}

webpack.config.js

module.exports = () => {
  return {
    entry: {
      index: './src/index.ts',
    },
    output: {
      filename: '[name].js',
      libraryTarget: 'umd',
      library: 'DummyComponent',
      umdNamedDefine: true,
    },
    resolve: {
      extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
    },
    devtool: 'source-map',
    module: {
      rules: [
        {
          test: /\.tsx?$/,
          // loader: 'awesome-typescript-loader',
          loader: 'ts-loader',
        },
      ],
    },
  };
};

Answer №1

It's been a while since anyone addressed this question. Since the latest version (9.4.3) of ts-loader, the issue has been resolved and all files are now generated directly under the dist folder, without any src subfolder. You can check out the updated test repository here: https://github.com/psalchow/ts-path-test

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

Angular 2: Musing on the potential of Hot Module Replacement and the power of @ngrx/store

If you're just getting started, this link might be helpful: understanding the purpose of HMR. When it comes to managing and designing large projects, I'm still in the early stages and haven't grown a wise beard yet. So, I'm seeking adv ...

Unable to adjust the x-axis time display in Chart.js

Within my ChartData Component, I am fetching data from an API and displaying it through a chart. The crucial aspect here is the determine Format Logic, which determines the time format of the data. My main challenge lies in changing the time display when s ...

I encountered an issue with my TypeScript function in Angular, as it is unable to process multiple uploaded files

I'm having trouble with my TypeScript function in Angular that is unable to read multiple uploaded files. fileUpload(event: Event) { const self = this; this.imageUploadInp = event.target as HTMLInputElement; this.imageUploadInp.addEventLis ...

Is it possible to transfer a URLFetchApp.fetch request from the Google Apps Script side to the JavaScript side?

My current task involves parsing an XML document tree upon clicking a button. The XML file is obtained using a lookup function that requires two values ("id" and "shipping") to be inserted into the appropriate URL. Then, the data retrieved is parsed using ...

A guide on how to implement promise return in redux actions for react native applications

I'm using redux to handle location data and I need to retrieve it when necessary. Once the location is saved to the state in redux, I want to return a promise because I require that data for my screen. Here are my actions, reducers, store setup, and ...

Unable to retrieve JSON data in servlet

I am having trouble passing variables through JSON from JSP to a servlet using an ajax call. Despite my efforts, I am receiving null values on the servlet side. Can someone please assist me in identifying where I may have gone wrong or what I might have ov ...

Angular's custom validator consistently returns a null value

I need help with validating the uniqueness of a username field in a form where an administrator can create a new user. I have implemented a uniqueUserNameValidator function for this purpose, but it always returns null. I suspect that the issue lies in the ...

While attempting to send a GET Request in Angular, access to XMLHttpRequest has been denied due to CORS policy restrictions

I am attempting to establish a GET method for my PHP API. Here is the code snippet I am using: export class PerfilComponent { perfil: any; constructor(private http: HttpClient) { } ngOnInit() { const token:string | null = localStorage.getItem(&ap ...

Wrong skill receives request instead of intended Alexa skill

Unexpectedly, the Alexa simulator has begun sending requests to other skills instead of mine. While I am able to invoke my skill and receive a response, any intent I try to use results in an audio-only response. Upon checking the server logs (hosted on Her ...

Generating a JSON file dynamically containing hierarchical data

I am looking to create a JSON file structure similar to the example provided in this post, but I need it to be dynamic. The current solution is specific for "entry1" and "entry2", however, I want the flexibility to use any entity name such as customer, add ...

What is the best way to display a loading screen while simultaneously making calls to multiple APIs?

I'm currently working with Angular 8 to develop an application that retrieves responses from various APIs for users. The application is designed to simultaneously call multiple APIs and I require a loading indicator that stops once each API delivers a ...

Enhancing Visuals with src="imageUrl within Html"

Is there a way to customize the appearance of images that are fetched from an API imageUrl? I would like to create some space between the columns but when the images are displayed on a medium to small screen, they appear too close together with no spacing. ...

Error: The function setIsEnabled does not exist

Currently, I am in the process of merging two separate next.js projects to create a website that can utilize the Cardano wallet 'Nami'. The code for accessing the wallet functions correctly in its original project, but when transferred over, it p ...

Is there a way to have my accordion adjust automatically?

I have developed a dynamic accordion component that populates its values from the parent component. However, I am facing an issue where each accordion does not respond individually to clicks. Whenever I click on any accordion, only the first one expands an ...

Employ a variable within the fetch method to retrieve JSON data

Currently, I am in the process of developing a system that extracts specific information from a JSON file based on user input. One challenge that I am facing is how to incorporate a variable into the designated section of my code; fetch( ...

Encountering compilation errors while using ng serve in NGCC

After attempting to update peer dependencies, I encountered an issue while compiling my Angular app. The error message displayed: Compiling @angular/material/core : es2015 as esm2015 Compiling @angular/material/expansion : es2015 as esm2015 Compiling @angu ...

What is the best way to create an array within an object during the parsing process

When working with a JSON object, I need to assign a value stored in the session against an ID. The JSON data is as follows: [ { "id": "a", "text": "a", "icon": true, "li_attr": { "id": "a" }, "a_attr": { "href": "#" ...

Retrieving a collection of names from the properties of a specific type

Looking to replicate the properties and values of a custom type in an object: type MyType = { propA: string; propB: string; propC: string; } const obj = { propA: "propA", propB: "propB", propC: "propC", } A type ...

Navigating to different HTML pages by utilizing <a> elements in Angular 2

As a newcomer to Angular 2, I've decided to build my personal website using this framework. The main page of my website contains bio information, while the other page will feature blog content. Both pages will have a shared header and footer, but diff ...

Issue with converting response to JSON format

I've encountered an issue while attempting to extract information from a React form and submit it to my Rails database. The error message "unexpected token '<' at position 0" suggests that the response is still in HTML format instead of J ...