Skip to content
This repository has been archived by the owner on Mar 20, 2024. It is now read-only.

JavaScript rules

Alex Eagle edited this page Mar 29, 2018 · 2 revisions

The JavaScript rules add the NodeJS runtime both for executing tools in the Bazel toolchain, as well as for building NodeJS applications.

Source location: [rules_nodejs]

_API Documentation: https://bazelbuild.github.io/rules_nodejs

Issues: https://github.com/bazelbuild/rules_nodejs/issues

Setup

For these rules to work, Bazel needs to partner with your package manager (Yarn or npm) so that dependencies are available to the toolchain. For example, the @bazel/typescript package on NPM provides the TypeScript bazel rules used below. That means we need to install the dependencies using the package manager before running the first build.

Then we need to tell Bazel how to find the rules, using a WORKSPACE file in the root of your workspace (typically that's the root of your repository), and then we need to declare a filegroup rule that tells Bazel how to find the installed dependencies in the node_modules directory.

See the Installation instructions for how to set up these prerequisites.

If you want to run bazel commands from the package.json scripts, you must take care not to lock the Bazel server in the initial bazel run @yarn... command. Otherwise the script will hang trying to run Bazel again underneath Bazel -- it is not re-entrant. See https://github.com/angular/tsickle/commit/d5ab3942c99ed991fa51fc4b21f9e4627afefeb8 for a workaround using the --script_path argument to bazel run.

Usage

The NodeJS rules ([rules_nodejs]) allow us to run JavaScript under Bazel, either as a tool that runs as part of the toolchain, or as a test or a binary program the users asks Bazel to execute.

nodejs_binary makes a runnable program based on some JS files and an entry point path, relative to the output root. To provide extra inputs which must be available to be read at runtime, put these in the data attribute. You can call this rule to produce a target that the user can run:

BUILD.bazel

nodejs_binary(
    name = "hello_world",
    ...
)
$ bazel run :hello_world
Hello, world!