Utilizing files that do not have the extension '.ts' or '.tsx' within the 'ts_library' as dependencies

My current challenge involves importing a JSON file from TypeScript while utilizing the resolveJsonModule flag in my tsconfig. The problem lies in how I can provide this JSON file to ts_library since it seems unable to locate the file. This issue extends to other non-.ts and .tsx files such as a .env.

For instance, consider this snippet of a ts_library within a BUILD.bazel file:

ts_library(
    name = "src",
    srcs = glob(["*.ts"]),
    deps = [
        "@npm//:node_modules",
    ]
)

accompanied by an index.ts like so:

import test from './test.json';

console.log(test);

and also a test.json with the content:

{
  "foo": "bar"
}

This setup triggers the following error message:

index.ts:1:18 - error TS2307: Cannot find module './test.json'.

I suspect that I need to somehow include the JSON file in the deps section of my rule. However, I am unsure how to go about it given that deps does not accept direct file references like //:test.json.

Answer №1

If you wish to incorporate files into the ts_library rule, you can achieve this by utilizing the data attribute (https://www.npmjs.com/package/@bazel/typescript#data). This is where the JSON file reference should be specified.

It is essential to understand that resolveJsonModule is only compatible with module formats like commonjs, amd, es2015, or esNext. Nevertheless, ts_library defaults to UMD and overrides this configuration.

The '--resolveJsonModule' option is confined to generating 'commonjs', 'amd', 'es2015', or 'esNext' modules.

To overcome this limitation, it is possible to directly employ the TypeScript compiler via Bazel instead of relying on ts_library:

load("@npm//typescript:index.bzl", "tsc")

srcs = glob(["*.ts"])
deps = ["@npm//@types/node"]
data = ["test.json"]

tsc(
    name = "src",
    data = srcs + deps + data,
    outs = [s.replace(".ts", ext) for ext in [".js", ".d.ts"] for s in srcs],
    args = [
        "--outDir",
        "$(RULEDIR)",
        "--lib",
        "es2017,dom",
        "--downlevelIteration",
        "--declaration",
        "--resolveJsonModule",
    ] + [
        "$(location %s)" % s
        for s in srcs
    ],
)

You can confirm its functionality by making use of the nodejs_binary:

load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_binary")

nodejs_binary(
    name = "src_bin",
    data = [
        ":src",
    ] + data,
    entry_point = "//src:index.ts",
)

For more comprehensive guidance on employing tsc rather than ts_library, refer to: https://github.com/bazelbuild/rules_nodejs/blob/master/packages/typescript/docs/install.md

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

Cross-origin resource sharing (CORS) seems to be creating a barrier for the communication between my Angular

During the process of developing an Angular and NestJS app with NGXS for state management, I encountered a CORS error while serving my application. The error message in the console indicated: Access to XMLHttpRequest at 'localhost:333/api/product-i ...

The Children Element in Next.js and React Context with TypeScript is lacking certain properties

Encountering a mysterious error while trying to implement React's Context API in Next.js with TypeScript. The issue seems to be revolving around wrapping the context provider around the _app.tsx file. Even though I am passing values to the Context Pr ...

Sending the HTML input value to a Knockout view

Can someone assist me with a dilemma I'm facing? Within CRM on Demand, I have a view that needs to extract values from CRM input fields to conduct a search against CRM via web service. If duplicate records are found, the view should display them. Be ...

Exploring a different approach to utilizing Ant Design Table Columns and ColumnGroups

As per the demo on how Ant Design groups columns, tables from Ant Design are typically set up using the following structure, assuming that you have correctly predefined your columns and data: <Table columns={columns} dataSource={data} // .. ...

Display a loading indicator with the shortest possible delay whenever utilizing the React Router v6 Link functionality

Integrate React and Router v6 App.tsx: const Page1 = lazy(() => pMinDelay(import('./views/Page1'), 500)) const Page2 = lazy(() => pMinDelay(import('./views/Page2'), 500)) return ( <Suspense fallback={<Loading/>}gt ...

"Error encountered: Route class unable to reach local function in TypeScript Express application" #codingissues

Experiencing an 'undefined' error for the 'loglogMePleasePlease' function in the code snippet below. Requesting assistance to resolve this issue. TypeError: Cannot read property 'logMePleasePlease' of undefined This error ...

What is the process for invoking an External Javascript Firestore function within a Typescript file?

Trying to figure out how to integrate a Firestore trigger written in an external JavaScript file (notifyNewMessage.js) into my TypeScript file (index.ts) using Node.js for Cloud functions. Both files are located in the same directory: https://i.stack.imgu ...

What could be causing the countdown timer to speed up unexpectedly?

Currently, I am developing a quiz application. At the moment, I need to implement the following features: Countdown timer Questions Question Choices The countdown timer for each question functions properly as long as the answer button is not clicked or ...

Tips on how to increase and update the index value by 2 within an ngFor loop while maintaining a fixed format

I have a specific template layout that displays only two items in each row as shown below. I want to use the ngFor directive to iterate through them: <div class="row" *ngFor="let item of cityCodes; let i = index"> <div class="col-6" (click)= ...

Clear pagination - results generated by the clr-dg-page-size component

I'm currently developing an Angular 8 application using Clarity UI. Within my app, I have implemented a datagrid with pagination. My challenge lies in fetching data after changing the number of items per page, as there is no output provided by the Cl ...

How can I load a separate component.html file using a component.ts file?

Hey there, I'm a beginner with Angular and I have a question about loading a different home.component.html file from a method within books.component.ts. Here's the code snippet from my books.component.ts file: import { Component, OnInit } from ...

Packaging a NodeJS project in Visual Studio - A step-by-step guide to creating and setting up an N

In my VS2013 solution, I have a combination of NodeJS (using TypeScript) and C# class library projects connected by EdgeJS. Among the NodeJS projects, one serves as a library for a RabbitMQ bus implementation, while two are applications meant to be hosted ...

Unable to fulfill the pledge

I'm struggling to receive the promise from the backend after making a get request. Can anyone help me figure out what I might be doing wrong? makeLoginCall(_username: string, _password: string) { let promise = new Promise((resolve, reject) => ...

Angular2: Once user is authenticated, navigate to specific routes

I've developed an admin panel with a router for page navigation. The layout of the admin panel includes a sidebar (Component), header (Component), and content (Component). Within the content, I have inserted <router-outlet></router-outlet> ...

Exploring the Nested JSON Data Loop with *ngFor in Angular 5/4

Recently I started working with Angular, and I've created a service to iterate over nested JSON data for my list. export const CATEGORIES: Category[] = [ { id: 1, categoryName:'Accessories', subcatName: [ {subcategory: & ...

Is it possible to alter the name of a slot before displaying the element in the shadowDOM, depending on the slot utilized in the DOM?

In my project, I am working on implementing different features for both desktop and mobile devices. Some of these features can be replaced by slots. My goal is to have a slot that can be either replaced by a desktop slot called poster-foreground, or a mobi ...

Importing/Requiring an External Module in Typescript Node using a Symbolic Link in the

I am in the process of migrating a Node + Express application to TypeScript and have encountered an issue with using external modules. Previously, I was utilizing the "symlink trick" to avoid dealing with relative paths. This is how it used to work withou ...

Creating components with the viewContainerRef in Angular2 is functioning as expected

When attempting to load a dynamic component into the root component using viewContainerRef.createComponent, I encountered an issue where it appended to the wrong place. https://i.stack.imgur.com/lF1yT.png Here is my code: -----app.compoment.ts----- exp ...

Issue with the MUI Autocomplete display in my form

Recently, I started using Material UI and Tailwind CSS for my project. However, I encountered an issue with the Autocomplete component where the input overlaps with the following DatePicker when there is multiple data in the Autocomplete. I have attached a ...

What are the distinctions between generic and discriminated types?

Hi there, I've been thinking of an idea but I'm not sure how to implement it or if it's even possible. Is there a way to create a type SomeType where the first property can be any value from the set T, but the second property cannot be the ...