What causes tsc to generate different json files based on its execution location?

Scenario: You have a typescript project set up to generate JSON files. The tsconfig.json is properly configured and all dependencies are in place. You've even referred to this related Q&A and ensured that your typescript files are importing the json files. However, when you run tsc, the json files are not being generated.

In an attempt to troubleshoot, you replicate the project in a different location with identical file structure and dependencies, and upon running tsc, the json files are successfully created. Puzzling situation!

Below is a simplified demonstration using node v16.13.2 and yarn v1.22.7

Reference Project

If you have nodejs and yarn installed, you can follow these steps:

pwd
# /tmp/foolib
yarn init -y  # initialize a new project
yarn add typescript  # only dependency needed for reproduction
export PATH=$(yarn bin):$PATH  # ensure `tsc` is in the path

Additional files required:

src/index.ts

import Thing from './moveme.json'
console.log("Hello")

src/moveme.json

{ "foo": "bar" }

tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "ES2015",
        "declarationMap": true,
        "esModuleInterop": true,
        "resolveJsonModule": true,
        "outDir": "./dist",
        "skipLibCheck": true,
        "declaration": true,
        "jsx": "react"
    },
    "include": [
        "src/**/*"
    ]
}

If you execute

rm -rf dist; export PATH=$(yarn bin):$PATH; tsc; find dist
, you should observe the following output:

dist
dist/index.d.ts
dist/index.d.ts.map
dist/moveme.json
dist/index.js

Another Project

Considering that you might be utilizing the project as a library elsewhere, let's mimic this scenario:

mkdir /tmp/fooproject
cd /tmp/fooproject
yarn init -y  # generates package.json, yarn.lock, node_modules
cp -R /tmp/foolib ./node_modules/  # create a local copy
cd node_modules/foolib
tsc

Upon running find dist, you'll notice:

dist
dist/index.d.ts
dist/index.d.ts.map
dist/index.js

Why isn't moveme.json present in the output?

Answer №1

Summary

When executing the tsc command from a location that includes a node_modules directory in its path, the JSON files will not be copied due to how tsc functions.

Solution

It is recommended to avoid running tsc from within a directory containing node_modules. However, if needed, compiling the code in a different location where node_modules is not part of the file path should resolve this issue quickly.

Explanation

During the execution of tsc, async workers are utilized to parse source files and determine code dependencies. If a referenced module like a JSON file is recognized as an "external library import," it will not be included in the output files.

This behavior is based on the presence of the term node_modules in the file path, making the file categorized as an external library import instead of being copied to the output folder.

Understanding this dependency on the file system structure up to the root level is crucial for maintaining the consistency of tsc's behavior across different working directories.

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

The Angular2 view is failing to display updated data from a shared service

I've been struggling to show data from my shared service, but it's not displaying. Can someone please help me out? I've been stuck on this for the past few days. I've tried NgZone and ChangeDetectorRef, but they haven't worked for ...

Angular2 and ReactiveX: Innovative Pagination Strategies

Currently, I am diving into the world of ReactiveX. To make things easier to understand, I have removed error checking, logging, and other unnecessary bits. One of my services returns a collection of objects in JSON format: getPanels() { return this. ...

Compiling fails when creating an object literal with a generic key

I am attempting to accomplish the following task. function createRecord<T extends string>(key: T) : Record<T, T> { return {[key]: key}; // Type '{ [x: string]: T; }' is not assignable to type 'Record<T, T>' } Howe ...

Increasing the value of a TypeScript variable using ngFor in an HTML template can enhance its usefulness

Can you dynamically increase a variable declared in your TypeScript file for each element generated by an ngFor loop in your HTML file? <tbody> <tr *ngFor="let item of invoiceItems"> <td>{{item.ItemName}}</td> <td>{ ...

Exploring the functionality of the Angular 7 date pipe in a more dynamic approach by incorporating it within a template literal using backticks, specifically

I have a value called changes.lastUpdatedTime.currentValue which is set to 1540460704884. I am looking to format this value using a pipe for date formatting. For example, I want to achieve something like this: {{lastUpdatedTime | date:'short'}} ...

Using Ionic 3 to create a list view that includes buttons linked to the items clicked

I need assistance with modifying the button icon in a list layout: <ion-list inset *ngFor="let audio of event.audios; let i = index"> <ion-item> <div class="item-text-center item-text-wrap"> {{audio.fileName}} </div& ...

Do I have to create all the classes returned when consuming a JSON web service in Angular/Typescript?

I would like to access this service: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY I am interested in extracting only two pieces of data: "location" : { " ...

The specified React element type is not valid

Currently working on a web application using Typescript, Electron, Webpack, and NodeJS, but encountering issues with the import/export functionality. The error message that I am facing reads: "Warning: React.createElement: type is invalid -- expect ...

Enhance your TypeScript arrays using custom object equality functions

I am looking to utilize array functions such as contains and unique, but I want them to compare equality using my custom equals function. For instance: let arr = [{id:1,..//some more},{id:2,..//some more},{id:3,..//some more}] I need the following code ...

I possess an item that I must display its title as a <choice> in a <menu> while returning a different variable

I am working with an object: company: { name: 'Google', id: '123asd890jio345mcn', } My goal is to display the company name as an option in a material-ui selector (Autocomplete with TextField rendering). However, when a user selects ...

Context for Apollo server has not been defined

Following the upgrade to Apollo v4 and migration guide, my project was functioning properly. However, the context is now undefined. const { url } = await startStandaloneServer(server, { listen: { port: 3000 }, context: async ({ req }) => { try ...

What is the preferred build tool to use with Deno?

It has come to my attention that deno no longer necessitates the use of package.json (compatible with npm/yarn) to detail its dependencies. However, when it comes to build/run scripts, is package.json still the recommended descriptor or are there alternat ...

Enhance the performance of your React/NextJS app by controlling the rendering of a component and focusing on updating

I'm facing an issue with my NextJS application that showcases a list of audio tracks using an <AudioTrackEntry> component. This component receives props like the Track Title and a Link to the audio file from an external data source. Within the ...

`Filter an array retrieved from the backend in a TypeScript environment`

I have asked other questions in the past, but I received unhelpful answers. I am still looking for proper solutions. Currently, I am retrieving an array from the backend using Redux. const { movies, message } = useAppSelector(state => state.movies); ...

Setting up gulp-typescript for Angular 2: A comprehensive guide

Right now I am utilizing the tsc compiler with the watch flag in the command prompt. It functions correctly, loading all definition files and successfully compiling each angular2 file. However, it is quite cumbersome to use via the shell window. My object ...

Guide to resolving typescript issue 'name' is not found in type 'ByRoleOptions' while accessing by name using getByRole in react-testing-library

I have a custom component that showcases a collection of filters in the form of removable chips. To test this functionality, I am utilizing react-testing-library with a focus on querying by accessible name as outlined here, using the getByRole method. The ...

Invoke cloud functions independently of waiting for a response

Attempting a clever workaround with cloud functions, but struggling to pinpoint the problem. Currently utilizing now.sh for hosting serverless functions and aiming to invoke one function from another. Let's assume there are two functions defined, fet ...

Is it possible to implement typed metaprogramming in TypeScript?

I am in the process of developing a function that takes multiple keys and values as input and should return an object with those keys and their corresponding values. The value types should match the ones provided when calling the function. Currently, the ...

Unable to locate the module 'next' or its associated type declarations

Encountering the error message Cannot find module '' or its corresponding type declarations. when trying to import modules in a Next.js project. This issue occurs with every single import. View Preview Yarn version: 3.1.0-rc.2 Next version: 1 ...

What is the best way to simulate a function within an object using Jest and Typescript?

I am currently working on a function that calls the url module. index.svelte import {url} from '@roxi/routify'; someFunction(() => { let x = $url('/books') // this line needs to be mocked console.log('x: ' + x); }); ...