Rollup faces challenges when trying to bundle source code alongside Bazel and Typescript

I am attempting to create a bundle using rollup, typescript, and bazel environment. I am having trouble importing relative paths. Typescript builds correctly but rollup is unable to bundle the source.

WORKSPACE

# WORKSPACE
workspace(
    name = "WORKSPACE",
    # Map the @npm bazel workspace to the node_modules directory.
    # This allows Bazel to use the same node_modules as other local tooling.
    managed_directories = {"@npm": ["node_modules"]},
)

# Imports
load("//tools:dependencies.bzl", "fetch_dependencies")
fetch_dependencies()

load("@build_bazel_rules_nodejs//:index.bzl", "yarn_install")
yarn_install(
    name = "npm",
    package_json = "//:package.json",
    yarn_lock = "//:yarn.lock",
)

# Set up web testing, choose browsers we can test on
load("@io_bazel_rules_webtesting//web:repositories.bzl", "web_test_repositories")

web_test_repositories()

load("@io_bazel_rules_webtesting//web/versioned:browsers-0.3.2.bzl", "browser_repositories")

browser_repositories(
    chromium = True,
    firefox = True,
)

FOLDER STRUCTURE

apps
    mobile
        index.ts
        src
            index.tsx
            asd.ts

packages
    core
        index.ts
        src
            index.ts
        ...

CORE BUILD FILE

# Package Info
package(default_visibility = ['//visibility:public'])

# Imports
load('@npm//@bazel/typescript:index.bzl', 'ts_library')
load('@build_bazel_rules_nodejs//:index.bzl', 'pkg_npm')

ts_library(
    name = "core",
    module_name = '@app/core',
    srcs = glob(["**/*.ts"]),
    deps = [
        "@npm//reflect-metadata",
        "@npm//moment",
        "@npm//rxjs",
        "@npm//axios",
    ]
)

pkg_npm(
    name = "core-package",
    srcs = [],
    substitutions = {"//internal/": "//"},
    deps = [
        '//packages/core:core'
    ],
)

APP BUILD FILE

# Package Info
package(default_visibility = ['//visibility:public'])

# Imports
load('@npm//@bazel/typescript:index.bzl', 'ts_library')
load("@npm//http-server:index.bzl", "http_server")
load("@npm//@bazel/rollup:index.bzl", "rollup_bundle")

ts_library(
    name = "mobile",
    module_name = '@app/mobile',
    srcs = glob(["**/*.ts", "**/*.tsx"]),
    deps = [
        "@npm//react",
        "@npm//@types/react",
        "@npm//react-router-dom",
        "@npm//@types/react-router-dom",
        "@npm//rxjs",
        "@npm//moment",

        "//packages/core:core",
    ]
)

filegroup(
    name = "mobile-source",
    srcs = [":mobile"],
    output_group = "es6_sources",
)

rollup_bundle(
    config_file = "//:rollup.config.js",
    name = "bundle",
    entry_points = {
        "index.ts" : "bundle"
    },
    srcs = [],
    output_dir = True,
    deps = [
        ":mobile",
        "@npm//@rollup/plugin-node-resolve"
    ],
)

http_server(
    name = "devserver",
    data = [
        "public/index.html",
        "bundle",
    ],
    args = ["."],
)

rollup.config.js

import { nodeResolve } from '@rollup/plugin-node-resolve';

export default {
    input: 'index.ts',
    output: {
        name: 'bundle',
        format: 'umd',
        plugins: [
            nodeResolve({
                mainFields: ['browser', 'es2015', 'module', 'jsnext:main', 'main'],
            })
        ]
    },
    onwarn: function (warning) {
        if (warning.code === 'THIS_IS_UNDEFINED') { return; }
        console.warn(warning.message);
    }
};

my index file in apps/mobile

export * from '@apps/mobile/src';
import { A } from './src/as';

console.log(A.a());

When I run bazel build //apps/mobile:bundle, I receive the following error and the bundle file is not completed.

bazel-out/k8-fastbuild/bin/apps/mobile/index.mjs → bazel-out/k8-fastbuild/bin/apps/mobile/bundle...
'@app/mobile/src' is imported by bazel-out/k8-fastbuild/bin/apps/mobile/index.mjs, but could not be resolved – treating it as an external dependency
The "buildStart" hook used by the output plugin node-resolve is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.
The "load" hook used by the output plugin node-resolve is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.
The "resolveId" hook used by the output plugin node-resolve is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.

GENRATED BUNDLE FILE

export * from '@apps/mobile/src';

class A {
    static a() {
        return 's';
    }
}

console.log(A.a());

Answer №1

After dedicating numerous hours to the problem, I finally discovered the solution. The ts_library rule includes parameters called devmode_target and devmode_module. When building in devmode, the ts_library does not reference configurations in the tsconfig file; instead, it looks at the values of devmode_target and devmode_module. By correctly setting these parameters (e.g. es2015), I was able to successfully build.

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

How to integrate a chips feature in Angular 4 using Typescript

Struggling to incorporate a chips component into my Angular web application, which comprises Typescript, HTML, and CSS files. After grappling with this for weeks without success, I have yet to find the right solution. To review my current code, you can a ...

Modify the interface type whilst maintaining the structure of nested objects

In my system, I have a specific interface that outlines the structure of a NoSQL document schema. This includes strings, arrays, nested objects, and more. Here's an example representation: interface IStudentSchema { name: string; age: string; f ...

Error message: Cypress Vue component test fails due to the inability to import the Ref type (export named 'Ref' is missing)

Recently, I created a Cypress component test for my Vue component by mounting it and verifying its existence. The component utilizes Vue's Ref type and is structured as a TypeScript component. However, during the test execution, Cypress encountered a ...

Tips on transitioning a Node.js application from JavaScript to TypeScript incrementally

I have a JavaScript node application that has grown quite large and I am considering migrating to TypeScript for faster development and easier code maintenance. I have installed TypeScript along with the node and mocha types using the following commands: ...

NextJS: Error - Unable to locate module 'fs'

Attempting to load Markdown files stored in the /legal directory, I am utilizing this code. Since loading these files requires server-side processing, I have implemented getStaticProps. Based on my research, this is where I should be able to utilize fs. Ho ...

Unable to export data from a TypeScript module in Visual Studio 2015 combined with Node.js

Within one file, I have the code snippet export class Foo{}. In another file: import {Foo} from "./module.ts"; var foo: Foo = new Foo(); However, when attempting to run this, I encountered the following error: (function (exports, require, module, __file ...

Angular (4, 5, 6, 7) - An easy guide to implementing slide in and out animations using ngIf

How can you implement a basic sliding animation in Angular4 to show and hide a container element? For example: <div *ngIf="show"> <!-- Content --> </div> Slide the content in (similar to jQuery's slideDown() method) from top t ...

Adding a new property to the Express request object type: what you need to know

Recently, I developed a custom middleware that executes specific logic tasks. It operates by transforming the keys to values and vice versa within the req.body. Both the keys and values are strings, with built-in validation measures in place for safety. T ...

How can a Firestore Timestamp object be correctly created within a rules test data set?

I am in the process of writing tests for Firestore rules, focusing on testing rules that control when actions can be executed based on a timestamp stored in the document. It is important to note that the rules will utilize rules.Timestamp rather than Java ...

Comparing TypeScript and C++ in terms of defining class reference member variables

class B; class A { A(B b_) : b{b_} {} B &b; }; In C++, it is possible to have a reference member variable like 'b' in class A. Can the same be achieved in TypeScript? Alternatively, is there a specific method to accomplish this in ...

My function won't get called when utilizing Angular

My Angular code is attempting to hide columns of a table using the function shouldHideColumn(). Despite my efforts, I am unable to bind my tags to the <th> and <td> elements. An error keeps popping up saying Can't bind to 'printerColu ...

Is it possible to easily organize a TypeScript dictionary in a straightforward manner?

My typescript dictionary is filled with code. var dictionaryOfScores: {[id: string]: number } = {}; Now that it's populated, I want to sort it based on the value (number). Since the dictionary could be quite large, I'm looking for an in-place ...

Warning: The parameter type in the Node JS project is not compatible with the argument type

Upon running this code in WebStorm, I encountered a warning: Argument type {where: {email: userData.emil}} is not assignable to parameter type NonNullFindOptions<Model["_attributes"]> Can someone explain this warning to me? This project ...

Angular Material Popup - Interactive Map from AGM

I am in the process of developing a material dialog to collect user location information using AGM (angular google maps). I have successfully implemented a map on my main page, but when the dialog is opened, it only shows a blank space instead of the map. ...

Properties are determined by both the type and sub-type

A challenging TypeScript challenge. Exploring Multiple Discriminated Union Types This task involves intersecting multiple discriminated union types together, where there exists a relationship between "types" and their corresponding "sub-types." The Main Q ...

Error message in TypeScript: A dynamic property name must be a valid type such as 'string', 'number', 'symbol', or 'any'

Attempting to utilize the computer property name feature in my TypeScript code: import {camelCase} from "lodash"; const camelizeKeys = (obj:any):any => { if (Array.isArray(obj)) { return obj.map(v => camelizeKeys(v)); } else if (ob ...

Use JavaScript's Array.filter method to efficiently filter out duplicates without causing any UI slowdown

In a unique case I'm dealing with, certain validation logic needs to occur in the UI for specific business reasons[...]. The array could potentially contain anywhere from several tens to hundreds of thousands of items (1-400K). This frontend operation ...

The Art of Typing in TypeScript Classes

I am working with an interface or abstract class in TypeScript, and I have numerous classes that implement or extend this interface/class. My goal is to create an array containing the constructors of all these subclasses, while still ensuring that the arra ...

Tips for properly waiting for an AngularFire2 subscription to complete before executing the subsequent lines of code within Angular2

Having an issue with my Angular2 Type Script code. The goal is to access Questions from a Firebase Database by subscribing to a FirebaseListObserver: this.af.list('/questions').subscribe( val => { this.questions = val console.log(th ...

Can someone confirm if I am importing this png file correctly? I am encountering an error with Vite, here is my code

Error: TypeScript+ React + Vite [plugin:vite:import-analysis] Failed to find import "./assets/heropic.png" in "src\components\Hero.tsx". Are you sure the file exists? Hello fellow developers! I am new to working with react and typescript. Curren ...