TypeScript rules for Bazel

The TypeScript rules integrate the TypeScript compiler with Bazel.

Alternatives

This package provides Bazel wrappers around the TypeScript compiler.

At a high level, there are four alternatives provided. This section describes the trade-offs between these rules.

Option 1: tsc

tsc is the TypeScript compiler published by the team at Microsoft. You can call it without any custom Bazel rules.

To use this option, you do not need to install the @bazel/typescript package.

The only reason to use raw tsc is if you want to compile a directory of .ts files and cannot enumerate them ahead-of-time in your BUILD file so that Bazel can predict all the output files. (For example if the .ts files are generated by some tool). This will produce an opaque directory of .js file outputs, which you won't be able to individually reference.

Any other use case for tsc is better served by using ts_project, see below.

Like we do for any npm package that exposes a binary, rules_nodejs will see your dependency on typescript and will generate an index.bzl file allowing you to run tsc. To use it, add the load statement load("@npm//typescript:index.bzl", "tsc") to your BUILD file. (Possibly replacing @npm with the name of the repository where you installed dependencies)

Then call it, using the npm_package_bin documentation.

Here is an example: https://github.com/bazelbuild/rules_nodejs/blob/3.2.2/internal/node/test/BUILD.bazel#L491-L507

Option 2: tsc_test

tsc_test is generated alongside tsc. It is identical, except that Bazel treats it as a test target, producing only an exit code rather than files to be consumed by other steps in the build.

This can be used for a build with --noEmit, so that TypeScript is purely used for type-checking and not for producing any build outputs.

To use it, add the load statement load("@npm//typescript:index.bzl", "tsc_test") to your BUILD file. (Possibly replacing @npm with the name of the repository where you installed dependencies)

To get the typings available in the test (as "runfiles"), you may need to gather them from dependencies if they are not included as default outputs of those dependencies, like so:

filegroup(name = "types", srcs = ["//some:js_library"], output_group = "types")

And then include the :types target in the data of the tsc_test.

See example in https://github.com/bazelbuild/rules_nodejs/tree/stable/packages/typescript/test/tsc_test

Option 3: ts_project

ts_project simply runs tsc --project, with Bazel knowing which outputs to expect based on the TypeScript compiler options, and with interoperability with other TypeScript rules via the DeclarationInfo Provider that transmits the type information.

It is intended as an easy on-boarding for existing TypeScript code and should be familiar if your background is in frontend ecosystem idioms.

Any behavior of ts_project should be reproducible outside of Bazel, with a couple of caveats noted in the rule documentation below.

ts_project is recommended for all new code.

Exhaustive examples of calling ts_project are in the test suite: https://github.com/bazelbuild/rules_nodejs/tree/stable/packages/typescript/test/ts_project

And there are also many uses of it in our

Option 4: ts_library

ts_library should not be used for new code, and may be deprecated in the future.

ts_library is an open-sourced version of the rule used to compile TS code at Google. However there is no support from the team that maintains that internal version. It is very complex, involving code generation of the tsconfig.json file, a custom compiler binary, and a lot of extra features.

It is also opinionated, and may not work with existing TypeScript code. For example:

  • Your TS code must compile under the --declaration flag so that downstream libraries depend only on types, not implementation. This makes Bazel faster by avoiding cascading rebuilds in cases where the types aren't changed.
  • We control the output format and module syntax so that downstream rules can rely on them.
  • Some other options are incompatible. For example you cannot use the --noEmit compiler option in tsconfig.json.

The only reason to use ts_library for new code is if you are bought-in to using a concatjs bundler, which requires the named AMD module format. This may be faster than other tooling, and this format can be consumed by the Closure Compiler (via integration with tsickle). However it is very challenging to configure and there is little available support for problems you'll run into.

Installation

Add a devDependency on @bazel/typescript

$ yarn add -D @bazel/typescript
# or
$ npm install --save-dev @bazel/typescript

Watch for any peerDependency warnings - we assume you have already installed the typescript package from npm.

Typical Usage

The ts_project rule invokes the TypeScript compiler on one compilation unit, or "library" (generally one directory of source files). In TypeScript terms, this is one "Project" which can use "Project References" to break up a large application.

Create a BUILD file next to your sources:

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

ts_project(
    name = "my_code",
    # glob is a quick way to select all the code,
    # but has performance penalty in that Bazel must evaluate it.
    srcs = glob(["*.ts"]),
    deps = ["//path/to/other:library"],
)

Here, //path/to/other:library is another target in your repo that produces TypeScript typings (for example, another ts_project rule). Be sure to set the rootDirs in your tsconfig.json as noted below, so that TypeScript can find the .d.ts files produced by that other target.

To use third-party libraries from npm, first install them (likely using npm_install or yarn_install rules) then add those to the deps as well:

ts_project(
    name = "my_code",
    srcs = glob(["*.ts"]),
    deps = [
      "@npm//@types/node",
      "@npm//@types/foo",
      "@npm//somelib",
      "//path/to/other:library",
    ],
)

You can also use the @npm//@types grouping target which will include all packages in the @types scope as dependencies.

To build a ts_library target run:

bazel build //path/to/package:target

Note that the tsconfig.json file used for compilation should be the same one your editor references, or extends from it, to keep consistent settings for the TypeScript compiler.

Anything you do with TypeScript is possible with ts_project, including json imports, type-checking only, transpile only, outdir, rootdir, and so on.

To use ts_project for typecheck-only, you'll still need to use --declaration so that .d.ts files are produced. Alternatively, see the tsc_test rule documented above.

See many examples in our test cases: https://github.com/bazelbuild/rules_nodejs/tree/stable/packages/typescript/test/ts_project

Rules

ts_config

Allows a tsconfig.json file to extend another file.

Normally, you just give a single tsconfig.json file as the tsconfig attribute of a ts_library or ts_project rule. However, if your tsconfig.json uses the extends feature from TypeScript, then the Bazel implementation needs to know about that extended configuration file as well, to pass them both to the TypeScript compiler.

Example usage (generated)

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

ts_config(
    # A unique name for this target.
    name = "",
    # The tsconfig.json file passed to the TypeScript compiler
    src = "",
)

name

A unique name for this target.

deps

Additional tsconfig.json files referenced via extends

src

The tsconfig.json file passed to the TypeScript compiler


Macros and Functions

ts_project

Compiles one TypeScript project using tsc --project

This is a drop-in replacement for the tsc rule automatically generated for the "typescript" package, typically loaded from @npm//typescript:index.bzl. Unlike bare tsc, this rule understands the Bazel interop mechanism (Providers) so that this rule works with others that produce or consume TypeScript typings (.d.ts files).

Unlike ts_library, this rule is the thinnest possible layer of Bazel interoperability on top of the TypeScript compiler. It shifts the burden of configuring TypeScript into the tsconfig.json file. See https://github.com/bazelbuild/rules_nodejs/blob/master/docs/TypeScript.md#alternatives for more details about the trade-offs between the two rules.

Some TypeScript options affect which files are emitted, and Bazel wants to know these ahead-of-time. So several options from the tsconfig file must be mirrored as attributes to ts_project. See https://www.typescriptlang.org/v2/en/tsconfig for a listing of the TypeScript options.

Any code that works with tsc should work with ts_project with a few caveats:

  • ts_project always produces some output files, or else Bazel would never run it. Therefore you shouldn't use it with TypeScript's noEmit option. See tsc_test under the Alternatives section above.
  • Bazel requires that the outDir (and declarationDir) be set to bazel-out/[target architecture]/bin/path/to/package so we override whatever settings appear in your tsconfig.
  • Bazel expects that each output is produced by a single rule. Thus if you have two ts_project rules with overlapping sources (the same .ts file appears in more than one) then you get an error about conflicting .js output files if you try to build both together. Worse, if you build them separately then the output directory will contain whichever one you happened to build most recently. This is highly discouraged.

Note: in order for TypeScript to resolve relative references to the bazel-out folder, we recommend that the base tsconfig contain a rootDirs section that includes all possible locations they may appear.

We hope this will not be needed in some future release of TypeScript. Follow https://github.com/microsoft/TypeScript/issues/37257 for more info.

For example, if the base tsconfig file relative to the workspace root is path/to/tsconfig.json then you should configure like:

"compilerOptions": {
    "rootDirs": [
        ".",
        "../../bazel-out/host/bin/path/to",
        "../../bazel-out/darwin-fastbuild/bin/path/to",
        "../../bazel-out/darwin_arm64-fastbuild/bin/path/to",
        "../../bazel-out/k8-fastbuild/bin/path/to",
        "../../bazel-out/x64_windows-fastbuild/bin/path/to",
        "../../bazel-out/darwin-dbg/bin/path/to",
        "../../bazel-out/k8-dbg/bin/path/to",
        "../../bazel-out/x64_windows-dbg/bin/path/to",
    ]
}

See some related discussion including both "rootDirs" and "paths" for a monorepo setup using custom import paths: https://github.com/bazelbuild/rules_nodejs/issues/2298

Issues when running non-sandboxed

When using a non-sandboxed spawn strategy (which is the default on Windows), you may observe these problems which require workarounds:

  1. Bazel deletes outputs from the previous execution before running tsc. This causes a problem with TypeScript's incremental mode: if the .tsbuildinfo file is not known to be an output of the rule, then Bazel will leave it in the output directory, and when tsc runs, it may see that the outputs written by the prior invocation are up-to-date and skip the emit of these files. This will cause Bazel to intermittently fail with an error that some outputs were not written. This is why we depend on composite and/or incremental attributes to be provided, so we can tell Bazel to expect a .tsbuildinfo output to ensure it is deleted before a subsequent compilation. At present, we don't do anything useful with the .tsbuildinfo output, and this rule does not actually have incremental behavior. Deleting the file is actually counter-productive in terms of TypeScript compile performance. Follow https://github.com/bazelbuild/rules_nodejs/issues/1726

  2. When using Project References, TypeScript will expect to verify that the outputs of referenced projects are up-to-date with respect to their inputs. (This is true even without using the --build option). When using a non-sandboxed spawn strategy, tsc can read the sources from other ts_project rules in your project, and will expect that the tsconfig.json file for those references will indicate where the outputs were written. However the outDir is determined by this Bazel rule so it cannot be known from reading the tsconfig.json file. This problem is manifested as a TypeScript diagnostic like error TS6305: Output file '/path/to/execroot/a.d.ts' has not been built from source file '/path/to/execroot/a.ts'. As a workaround, you can give the Windows "fastbuild" output directory as the outDir in your tsconfig file. On other platforms, the value isn't read so it does no harm. See https://github.com/bazelbuild/rules_nodejs/tree/stable/packages/typescript/test/ts_project as an example. We hope this will be fixed in a future release of TypeScript; follow https://github.com/microsoft/TypeScript/issues/37378

  3. When TypeScript encounters an import statement, it adds the source file resolved by that reference to the program. However you may have included that source file in a different project, so this causes the problem mentioned above where a source file is in multiple programs. (Note, if you use Project References this is not the case, TS will know the referenced file is part of the other program.) This will result in duplicate emit for the same file, which produces an error since the files written to the output tree are read-only. Workarounds include using using Project References, or simply grouping the whole compilation into one program (if this doesn't exceed your time budget).

Example usage (generated)

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

ts_project(
)

name

A name for the target.

We recommend you use the basename (no .json extension) of the tsconfig file that should be compiled.

tsconfig

Label of the tsconfig.json file to use for the compilation

To support "chaining" of more than one extended config, this label could be a target that provides TsConfigInfo such as ts_config.

By default, we assume the tsconfig file is "tsconfig.json" in the same folder as the ts_project rule.

EXPERIMENTAL: generated tsconfig

Instead of a label, you can pass a dictionary of tsconfig keys.

In this case, a tsconfig.json file will be generated for this compilation, in the following way:

  • all top-level keys will be copied by converting the dict to json. So tsconfig = {"compilerOptions": {"declaration": True}} will result in a generated tsconfig.json with {"compilerOptions": {"declaration": true}}
  • each file in srcs will be converted to a relative path in the files section.
  • the extends attribute will be converted to a relative path

Note that you can mix and match attributes and compilerOptions properties, so these are equivalent:

ts_project(
    tsconfig = {
        "compilerOptions": {
            "declaration": True,
        },
    },
)

and

ts_project(
    declaration = True,
)

srcs

List of labels of TypeScript source files to be provided to the compiler.

If absent, the default is set as follows:

  • Include **/*.ts[x] (all TypeScript files in the package).
  • If allow_js is set, include **/*.js[x] (all JavaScript files in the package).
  • If resolve_json_module is set, include **/*.json (all JSON files in the package), but exclude **/package.json, **/package-lock.json, and **/tsconfig*.json.

args

List of strings of additional command-line arguments to pass to tsc.

deps

List of labels of other rules that produce TypeScript typings (.d.ts files)

extends

Label of the tsconfig file referenced in the extends section of tsconfig

To support "chaining" of more than one extended config, this label could be a target that provdes TsConfigInfo such as ts_config.

allow_js

boolean; Specifies whether TypeScript will read .js and .jsx files. When used with declaration, TypeScript will generate .d.ts files from .js files.

declaration

if the declaration bit is set in the tsconfig. Instructs Bazel to expect a .d.ts output for each .ts source.

source_map

if the sourceMap bit is set in the tsconfig. Instructs Bazel to expect a .js.map output for each .ts source.

declaration_map

if the declarationMap bit is set in the tsconfig. Instructs Bazel to expect a .d.ts.map output for each .ts source.

resolve_json_module

None | boolean; Specifies whether TypeScript will read .json files. Defaults to None. If set to True or False and tsconfig is a dict, resolveJsonModule is set in the generated config file. If set to None and tsconfig is a dict, resolveJsonModule is unset in the generated config and typescript default or extended tsconfig value will be load bearing.

preserve_jsx

if the jsx value is set to "preserve" in the tsconfig. Instructs Bazel to expect a .jsx or .jsx.map output for each .tsx source.

composite

if the composite bit is set in the tsconfig. Instructs Bazel to expect a .tsbuildinfo output and a .d.ts output for each .ts source.

incremental

if the incremental bit is set in the tsconfig. Instructs Bazel to expect a .tsbuildinfo output.

emit_declaration_only

if the emitDeclarationOnly bit is set in the tsconfig. Instructs Bazel not to expect .js or .js.map outputs for .ts sources.

transpiler

A custom transpiler tool to run that produces the JavaScript outputs instead of tsc.

This attribute accepts a rule or macro with this signature: name, srcs, js_outs, map_outs, **kwargs where the **kwargs attribute propagates the tags, visibility, and testonly attributes from ts_project.

If you need to pass additional attributes to the transpiler rule, you can use a partial to bind those arguments at the "make site", then pass that partial to this attribute where it will be called with the remaining arguments. See the packages/typescript/test/ts_project/swc directory for an example.

When a custom transpiler is used, then the ts_project macro expands to these targets:

  • [name] - the default target is a js_library which can be included in the deps of downstream rules. Note that it will successfully build even if there are typecheck failures because the tsc binary is not needed to produce the default outputs. This is considered a feature, as it allows you to have a faster development mode where type-checking is not on the critical path.
  • [name]_typecheck - provides typings (.d.ts files) as the default output, therefore building this target always causes the typechecker to run.
  • [name]_typecheck_test - a build_test target which simply depends on the [name]_typecheck target. This ensures that typechecking will be run under bazel test with --build_tests_only.
  • [name]_typings - internal target which runs the binary from the tsc attribute
  • Any additional target(s) the custom transpiler rule/macro produces. Some rules produce one target per TypeScript input file.

By default, ts_project expects .js outputs to be written in the same action that does the type-checking to produce .d.ts outputs. This is the simplest configuration, however tsc is slower than alternatives. It also means developers must wait for the type-checking in the developer loop.

In theory, Persistent Workers (via the supports_workers attribute) remedies the slow compilation time, however it adds additional complexity because the worker process can only see one set of dependencies, and so it cannot be shared between different ts_project rules. That attribute is documented as experimental, and may never graduate to a better support contract.

ts_build_info_file

the user-specified value of tsBuildInfoFile from the tsconfig. Helps Bazel to predict the path where the .tsbuildinfo output is written.

tsc

Label of the TypeScript compiler binary to run.

For example, tsc = "@my_deps//typescript/bin:tsc" Or you can pass a custom compiler binary instead.

One possible compiler is the Angular compiler, provided by the @angular/compiler-cli package as the ngc binary, which can be set typically with tsc = "@npm//@angular/compiler-cli/bin:ngc" Note that you'll also need to pass .html and .css files to the srcs of the ts_project so that they're declared as inputs for the Angular compiler to read them.

An example can be found in the rules_nodejs repo under packages/typescript/test/ts_project/ngc.

To use the ngc program from Angular versions prior to 11, you'll need a fix for https://github.com/angular/angular/issues/36290 To apply the fix, you can use the patch-package package to apply this patch: https://gist.github.com/alexeagle/ba44b2601bd7c953d29c6e8ec44d1ef9

typescript_package

Label of the package containing all data deps of tsc.

For example, typescript_package = "@my_deps//typescript"

typescript_require_path

Module name which resolves to typescript_package when required

For example, typescript_require_path = "typescript"

validate

boolean; whether to check that the tsconfig JSON settings match the attributes on this target.

Set this to False to skip running our validator, in case you have a legitimate reason for these to differ, e.g. you have a setting enabled just for the editor but you want different behavior when Bazel runs tsc.

supports_workers

Experimental! Use only with caution.

Allows you to enable the Bazel Persistent Workers strategy for this project. See https://docs.bazel.build/versions/main/persistent-workers.html

This requires that the tsc binary support a --watch option.

NOTE: this does not work on Windows yet. We will silently fallback to non-worker mode on Windows regardless of the value of this attribute. Follow https://github.com/bazelbuild/rules_nodejs/issues/2277 for progress on this feature.

declaration_dir

a string specifying a subdirectory under the bazel-out folder where generated declaration outputs are written. Equivalent to the TypeScript --declarationDir option. By default declarations are written to the out_dir.

out_dir

a string specifying a subdirectory under the bazel-out folder where outputs are written. Equivalent to the TypeScript --outDir option. Note that Bazel always requires outputs be written under a subdirectory matching the input package, so if your rule appears in path/to/my/package/BUILD.bazel and out_dir = "foo" then the .js files will appear in bazel-out/[arch]/bin/path/to/my/package/foo/*.js. By default the out_dir is '.', meaning the packages folder in bazel-out.

root_dir

a string specifying a subdirectory under the input package which should be consider the root directory of all the input files. Equivalent to the TypeScript --rootDir option. By default it is '.', meaning the source directory where the BUILD file lives.

Link the workspace root to the bin_dir to support absolute requires like 'my_wksp/path/to/file'. If source files need to be required then they can be copied to the bin_dir with copy_to_bin.

kwargs

passed through to underlying rule, allows eg. visibility, tags