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

Exploring the concept of kleisli composition in TypeScript by combining Promise monad with functional programming techniques using fp-ts

Is there a way to combine two kleisli arrows (functions) f: A -> Promise B and g: B -> Promise C into h: A -> Promise C using the library fp-ts? Having experience with Haskell, I would formulate it as: How can I achieve the equivalent of the > ...

How can the panel within an accordion be enlarged or minimized?

Currently, I am implementing an accordion feature with the option to expand or collapse all panels using two buttons. My goal is to allow users to manage each panel within the accordion individually. However, I have encountered an issue that needs attenti ...

Exciting Update: Next.js V13 revalidate not triggering post router.push

Currently using Next.js version 13 for app routing, I've encountered an issue with the revalidate feature not triggering after a router.push call. Within my project, users have the ability to create blog posts on the /blog/create page. Once a post is ...

Parsing JSON results in the return of two objects

I am analyzing a JSON file, expecting it to return Message[] using a promise. This code is similar to the one utilized in the Heroes sample project found in HTTP documentation { "data": [ {"id":"1","commid":"0","subject":"test1subject","body":" ...

What is the correct way to integrate knex using inversify?

Is there a way for me to set up knex and utilize the Inversify dependency injector to inject it wherever it is required? ...

What is the process for sending an HTTP post request with a React/Typescript frontend and a C#/.Net backend?

In the frontend code, there is a user login form that accepts the strings email and password. Using MobX State Management in the userstore, there is an action triggered when the user clicks the login button to submit the strings via HTTP post. @action logi ...

Types with conditions but no common parameter

I am looking to define my props as either type A or B. For instance export default function App() { type Checkbox = { type: "checkbox"; checked: boolean; }; type Dropdown = { type: "dropdown"; options: Array<an ...

How to Nest Interfaces in TypeScript

I'm just starting to learn about Angular and I am having trouble getting the interface class to work properly. export interface Header { parentTitles: string; childHeaders: ChildHeader[]; titleIcon: string; url: string; } export interf ...

Enhance your Angular material datepicker with additional content such as a close button

I'm currently working on customizing my Angular Material datepicker by adding a button. The goal is to have this button placed in the top right corner and enable it to close the datepicker when clicked. In addition, I also want to include extra conte ...

Typescript is struggling to locate a module that was specified in the "paths" configuration

Within my React project, I have set up a module alias in the webpack config. Now, I am looking to transition to Typescript. // I have tried to simplify the setup as much as possible Here is my tsconfig.json located in the root directory: { "compilerOp ...

Is there a way to efficiently compare multiple arrays in Typescript and Angular?

I am faced with a scenario where I have 4 separate arrays and need to identify if any item appears in more than two of the arrays. If this is the case, I must delete the duplicate items from all arrays except one based on a specific property. let arrayA = ...

tsc does not support the use of the '--init' command option

Encountering an error when running npx tsc --init: $ npx tsc --init npx: installed 1 in 1.467s error TS5023: Unknown compiler option 'init'. I've added the typescript package using Yarn 2: $ yarn add -D typescript ➤ YN0000: ┌ Resolution ...

Utilizing Office.js: Incorporating Angular CLI to Call a Function in a Generated Function-File

After using angular-cli to create a new project, I integrated ng-office-ui-fabric and its dependencies. I included in index.html, added polyfills to angular.json, and everything seemed to be working smoothly. When testing the add-in in Word, the taskpane ...

Looking to merge two components into one single form using Angular?

I am currently developing an Angular application with a dynamic form feature. The data for the dynamic form is loaded through JSON, which is divided into two parts: part 1 and part 2. // JSON Data Part 1 jsonDataPart1: any = [ { "e ...

Activate function on Ctrl + K in a React TypeScript project

I am currently developing a React TypeScript application using version v18.2.0. My goal is to trigger a function when the user simultaneously presses Ctrl + K. Here is the code snippet within my component: const keyDownHandler = (event: KeyboardEvent) =& ...

How to dynamically retrieve values from a const object literal using TypeScript

Currently, I am utilizing a TypeScript library known as ts-proto, which is responsible for generating TypeScript code. The resulting generated code resembles the following: //BasicMessage.ts export interface BasicMessage { id: Long; name: string; } ...

Navigating through a React application with several workspaces - the ultimate guide

Currently, I am working on implementing a monorepo setup inspired by this reference: https://github.com/GeekyAnts/nativebase-templates/tree/master/solito-universal-app-template-nativebase-typescript In this repository, there are 4 distinct locations wher ...

Access Select without needing to click on the child component

I am curious to learn how to open a Select from blueprint without relying on the click method of the child component used for rendering the select. <UserSelect items={allUsers} popoverProps={{ minimal: false }} noResults={<MenuItem disabled={ ...

Best Method for Confirming Deletion in Data Table with Shadow and UI

I have a query regarding the Shadcn/UI - Data Table component. In my case, I am working with a list of users where each row has a delete button in the last column. Upon clicking the delete button, a confirmation dialog pops up. Currently, I am implementi ...

Is there a way for me to implement a "view more posts" button on

I need help figuring out how to hide the "Show More" button when there are no posts. I have created a showLoad function and an isLoad state variable, but I'm unsure of how to implement this. The button display logic is dependent on the isLoad state. ...