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

What is the best way to incorporate data from JSON objects in nested arrays within an array into HTML using AngularJS?

I have been struggling to display the JSON data in list.html in the desired format. Despite trying different approaches from similar posts, I have not been successful as my JSON structure is unique. How can I ensure that fields such as givenName, familyNam ...

Declaration of dependencies for NestJS must include dependencies of dependencies

I'm encountering an issue where NestJS is not automatically resolving dependencies-of-dependencies: I have created an AWSModule which is a simple link to Amazon AWS with only a dependency on the ConfigService: @Module({ imports: [ConfigModule], ...

transfer extra information to Laravel resource

I am trying to pass my custom data to the same level of an array of resource, but it is getting placed outside of the array. return CategoryProductsResource::collection(Category::whereNull('parent_id')->get()) ->additional([ ...

Error! Element not found in cloned iframe #2460, promise unhandled

Can you help me troubleshoot this issue? This is the code I'm working with: const section = document.createElement("section"); const myHTMLCode = "<p>Greetings</p>"; section.insertAdjacentHTML("afterbegin", my ...

Issue: Incompatibility between 'System.IO.Stream' and 'String' types

I've hit a roadblock and could really use some help. Despite hours of searching online and reading through documentation, I haven't been able to find a solution. The error message I'm encountering is from the "response" overload entry in th ...

How can a parent's method be activated only after receiving an event emitter from the child and ensuring that the parent's ngIf condition is met?

Every time the element in the child template is clicked, it triggers the method activateService(name) and emits an event with the name of the selected service using the event emitter serviceSelected. The parent component's method scrollDown(name) is t ...

"Why don't JSON support comments? It seems like developers used to communicate instructions to the parser using them." Can someone clarify this concept for me?

Can someone help me understand why Comments are removed in JSON even though some parsers can read them? Douglas Crawford mentioned that it's to prevent passing instructions to parsers through comments. Does anyone have more insight on this? ...

A script object must only permit one property at a time

I am unfamiliar with TypeScript and I have an object named obj with 3 properties: a, b, c. However, it is important to note that b and c cannot exist together in the same object. So, my object will either be: obj = { a: 'xxx', b: 'x ...

Upgrade Challenge from Angular 7 to Angular 9

I am currently in the process of upgrading my application from version 7 to version 9. However, I have encountered an issue with the new IVY compiler in Angular 9 not being compatible with the library angular-webstorage-service, resulting in the following ...

Angular 4 and the process of HTML encoding

Looking for assistance with html encoding in angular 4. I have product records stored in a database, with the fullDescription field in this particular format: &lt;div align="justify"&gt;&lt;span&gt; When using <div *ngIf="product" [inn ...

I am facing errors while running npm run build in my Vue CLI project, however, npm run dev is running smoothly without

I am encountering an issue when running npm run build as it generates a series of errors, whereas npm run dev runs smoothly without any errors. I have attempted to resolve this by modifying the public path in webpack.config.js to ./dist, but unfortunately ...

Utilizing Highcharts to display multiple series data extracted from JSON

After retrieving JSON data from an API endpoint, my goal is to have Highcharts create a new series for each JSON array received. The specific JSON structure I'm working with looks like this: [[[773,1363709520],[774,1363709580]],[[1546,1363709520],[154 ...

Replace the default Material UI 5.0 typography theme with custom fonts on a global scale

My current challenge involves incorporating two personal fonts into the Material UI 5.0. My goal is to apply these fonts globally by overriding the theme settings. However, I have encountered issues with loading the fonts properly and modifying the typogra ...

Encountering a webpack mix issue on Ubuntu version 18

Whenever I try to execute the command ( npm run watch ), I encounter this error: @ development /home/nader/Desktop/asd/blog cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setu ...

Tips on selecting specific data from a nested JSON array based on conditions and fetching just one value from the initial filtered result with Javascript (designed for Google Sheets)

Utilizing the TMDB API for retrieving movie data and integrating it into a Google Sheet. The original Google Sheet was revamped from Reddit user 6745408's "MediaSheet 3.0". This sheet incorporates a Javascript-based script. By following the patterns/c ...

While working on a JSON project in Xcode, I encountered an error in the first part of my sample

I encountered the error below: Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised leading character\" UserInfo=0x6a2b1a0 {NSLocalizedDescription=Unrecognised leading character} Could you kindly explain the meaning of this error ...

The ActivatedRoute snapshot does not function properly when used in the TypeScript class constructor

Currently, I am encountering a challenge with TypeScript and Angular 2. The structure of my TS class is as follows: 'import { Component, OnInit } from '@angular/core'; import {ActivatedRoute} from '@angular/router'; @Component({ ...

Retrieving data from an Array

I've encountered a peculiar issue while working on a test project. It seems that I am unable to access values in an array. pokemonStats$: Observable<PokemonStats[]>; getPokemonStats(id: number): any { this.pokemonStats$ .pipe(take(1)) .subscrib ...

Tips for accessing a specific ListItem within the Menu Component using MUI for React

Within my code, I am working with a List that contains multiple ListItems pulled from an array called myCollection. Each ListItem has a MenuIcon element which triggers a menu to appear, providing the option to delete the specific item. Here is a simplified ...

Export multiple variables at once

Within TypeScript, I have Class1 defined in class.ts, along with some functions from helper.ts and variables from variables.ts: For instance, the content of variables.ts is as follows: export const test1 = 'test1'; export const test2 = 0; expor ...