These rules are available without any npm installation, via the WORKSPACE install of the build_bazel_rules_nodejs workspace. This is necessary to bootstrap Bazel to run the package manager to download other rules from NPM.
To be run in user's WORKSPACE to install rules_nodejs dependencies.
This rule sets up node, npm, and yarn.
The versions of these tools can be specified in one of three ways:
This rule exposes the @nodejs workspace containing some rules the user can call later:
bazel run @nodejs//:node path/to/program.jsbazel run @nodejs//:npm installbazel run @nodejs//:yarnNote that the dependency installation scripts will run in each subpackage indicated by the package_json attribute.
This approach uses npm/yarn as the package manager. You could instead have Bazel act as the package manager, running the install behind the scenes. See the npm_install and yarn_install rules, and the discussion in the README.
Example:
load("@build_bazel_rules_nodejs//:index.bzl", "node_repositories")
node_repositories(package_json = ["//:package.json", "//subpkg:package.json"])
Running bazel run @nodejs//:yarn in this repo would create /node_modules and /subpkg/node_modules.
node_repositories(name, node_repositories, node_urls, node_version, package_json, preserve_symlinks, vendored_node, vendored_yarn, yarn_repositories, yarn_urls, yarn_version)
name(name, mandatory): A unique name for this repository.
node_repositories(Dictionary: String -> List of strings): Custom list of node repositories to use
A dictionary mapping NodeJS versions to sets of hosts and their corresponding (filename, strip_prefix, sha256) tuples. You should list a node binary for every platform users have, likely Mac, Windows, and Linux.
For example,
node_repositories( node_repositories = { "10.10.0-darwin_amd64": ("node-v10.10.0-darwin-x64.tar.gz", "node-v10.10.0-darwin-x64", "00b7a8426e076e9bf9d12ba2d571312e833fe962c70afafd10ad3682fdeeaa5e"), "10.10.0-linux_amd64": ("node-v10.10.0-linux-x64.tar.xz", "node-v10.10.0-linux-x64", "686d2c7b7698097e67bcd68edc3d6b5d28d81f62436c7cf9e7779d134ec262a9"), "10.10.0-windows_amd64": ("node-v10.10.0-win-x64.zip", "node-v10.10.0-win-x64", "70c46e6451798be9d052b700ce5dadccb75cf917f6bf0d6ed54344c856830cfb"), }, )
node_urls(List of strings): custom list of URLs to use to download NodeJS
Each entry is a template for downloading a node distribution.
The {version} parameter is substituted with the node_version attribute, and {filename} with the matching entry from the node_repositories attribute.
For example, given
node_repositories( node_version = "10.10.0", node_repositories = {"10.10.0-darwin_amd64": ("node-v10.10.0-darwin-x64.tar.gz", "node-v10.10.0-darwin-x64", "00b7a8426e076e9bf9d12ba2d571312e833fe962c70afafd10ad3682fdeeaa5e")}, node_urls = ["https://mycorpproxy/mirror/node/v{version}/{filename}"], )
A Mac client will try to download node from https://mycorpproxy/mirror/node/v10.10.0/node-v10.10.0-darwin-x64.tar.gz and expect that file to have sha256sum 00b7a8426e076e9bf9d12ba2d571312e833fe962c70afafd10ad3682fdeeaa5e
node_version(String): the specific version of NodeJS to install or, if vendored_node is specified, the vendored version of node
package_json(labels): a list of labels, which indicate the package.json files that will be installed when you manually run the package manager, e.g. with bazel run @nodejs//:yarn or bazel run @nodejs//:npm install. If you use bazel-managed dependencies, you can omit this attribute.
preserve_symlinks(Boolean): Turn on --node_options=--preserve-symlinks for nodejs_binary and nodejs_test rules.
The default for this is currently True but the options is deprecated and will be removed in the future.
When this option is turned on, node will preserve the symlinked path for resolves instead of the default behavior of resolving to the real path. This means that all required files must be in be included in your runfiles as it prevents the default behavior of potentially resolving outside of the runfiles. For example, all required files need to be included in your node_modules filegroup. This option is desirable as it gives a stronger guarantee of hermiticity which is required for remote execution.
vendored_node(label): the local path to a pre-installed NodeJS runtime.
If set then also set node_version to the version that of node that is vendored. Bazel will automatically turn on features such as --preserve-symlinks-main if they are supported by the node version being used.
vendored_yarn(label): the local path to a pre-installed yarn tool
yarn_repositories(Dictionary: String -> List of strings): Custom list of yarn repositories to use.
Dictionary mapping Yarn versions to their corresponding (filename, strip_prefix, sha256) tuples.
For example,
node_repositories( yarn_repositories = { "1.12.1": ("yarn-v1.12.1.tar.gz", "yarn-v1.12.1", "09bea8f4ec41e9079fa03093d3b2db7ac5c5331852236d63815f8df42b3ba88d"), }, )
yarn_urls(List of strings): custom list of URLs to use to download Yarn
Each entry is a template, similar to the node_urls attribute, using yarn_version and yarn_repositories in the substitutions.
For example,
node_repositories( yarn_repositories = { "1.12.1": ("yarn-v1.12.1.tar.gz", "yarn-v1.12.1", "09bea8f4ec41e9079fa03093d3b2db7ac5c5331852236d63815f8df42b3ba88d"), }, yarn_version = "1.12.1", yarn_urls = "https://github.com/yarnpkg/yarn/releases/download/v{version}/{filename}", )
Will download yarn from https://github.com/yarnpkg/yarn/releases/download/v1.2.1/yarn-v1.12.1.tar.gzand expect the file to have sha256sum09bea8f4ec41e9079fa03093d3b2db7ac5c5331852236d63815f8df42b3ba88d`.
yarn_version(String): the specific version of Yarn to install
Runs some JavaScript code in NodeJS.
nodejs_binary(name, bootstrap, configuration_env_vars, data, default_env_vars, entry_point, install_source_map_support, node_modules, templated_args, templated_args_file)
name(name, mandatory): A unique name for this target.
bootstrap(List of strings): JavaScript modules to be loaded before the entry point. For example, Angular uses this to patch the Jasmine async primitives for zone.js before the first describe.
configuration_env_vars(List of strings): Pass these configuration environment variables to the resulting binary. Chooses a subset of the configuration environment variables (taken from ctx.var), which also includes anything specified via the --define flag. Note, this can lead to different outputs produced by this rule.
data(labels): Runtime dependencies which may be loaded during execution.
default_env_vars(List of strings): Default environment variables that are added to configuration_env_vars.
This is separate from the default of configuration_env_vars so that a user can set configuration_env_vars without losing the defaults that should be set in most cases.
The set of default environment variables is:
DEBUG: rules use this environment variable to turn on debug information in their output artifactsVERBOSE_LOGS: rules use this environment variable to turn on debug output in their logsentry_point(label, mandatory): The script which should be executed first, usually containing a main function.
If the entry JavaScript file belongs to the same package (as the BUILD file), you can simply reference it by its relative name to the package directory:
nodejs_binary(
name = "my_binary",
...
entry_point = ":file.js",
)
You can specify the entry point as a typescript file so long as you also include the ts_library target in data:
ts_library(
name = "main",
srcs = ["main.ts"],
)
nodejs_binary(
name = "bin",
data = [":main"]
entry_point = ":main.ts",
)
The rule will use the corresponding .js output of the ts_library rule as the entry point.
If the entry point target is a rule, it should produce a single JavaScript entry file that will be passed to the nodejs_binary rule. For example:
filegroup(
name = "entry_file",
srcs = ["main.js"],
)
nodejs_binary(
name = "my_binary",
entry_point = ":entry_file",
)
The entry_point can also be a label in another workspace:
nodejs_binary(
name = "history-server",
entry_point = "@npm//:node_modules/history-server/modules/cli.js",
data = ["@npm//history-server"],
)
install_source_map_support(Boolean): Install the source-map-support package. Enable this to get stack traces that point to original sources, e.g. if the program was written in TypeScript.
node_modules(label): The npm packages which should be available to require() during execution.
This attribute is DEPRECATED. As of version 0.13.0 the recommended approach to npm dependencies is to use fine grained npm dependencies which are setup with the yarn_install or npm_install rules. For example, in targets that used a //:node_modules filegroup,
nodejs_binary(
name = "my_binary",
...
node_modules = "//:node_modules",
)
which specifies all files within the //:node_modules filegroup to be inputs to the my_binary. Using fine grained npm dependencies, my_binary is defined with only the npm dependencies that are needed:
nodejs_binary(
name = "my_binary",
...
data = [
"@npm//foo",
"@npm//bar",
...
],
)
In this case, only the foo and bar npm packages and their transitive deps are includes as inputs to the my_binary target which reduces the time required to setup the runfiles for this target (see https://github.com/bazelbuild/bazel/issues/5153).
The @npm external repository and the fine grained npm package targets are setup using the yarn_install or npm_install rule in your WORKSPACE file:
yarn_install( name = “npm”, package_json = “//:package.json”, yarn_lock = “//:yarn.lock”, )
For other rules such as jasmine_node_test, fine grained npm dependencies are specified in the deps attribute:
jasmine_node_test(
name = "my_test",
...
deps = [
"@npm//jasmine",
"@npm//foo",
"@npm//bar",
...
],
)
templated_args(List of strings): Arguments which are passed to every execution of the program. To pass a node startup option, prepend it with --node_options=, e.g. --node_options=--preserve-symlinks
templated_args_file(Label): If specified, arguments specified in templated_args are instead written to this file, which is then passed as an argument to the program. Arguments prefixed with --node_options= are passed directly to node and not included in the params file.
Identical to nodejs_binary, except this can be used with bazel test as well. When the binary returns zero exit code, the test passes; otherwise it fails.
nodejs_test is a convenient way to write a novel kind of test based on running your own test runner. For example, the ts-api-guardian library has a way to assert the public API of a TypeScript program, and uses nodejs_test here: https://github.com/angular/angular/blob/master/tools/ts-api-guardian/index.bzl
If you just want to run a standard test using a test runner like Karma or Jasmine, use the specific rules for those test runners, e.g. jasmine_node_test.
To debug a Node.js test, we recommend saving a group of flags together in a “config”. Put this in your tools/bazel.rc so it's shared with your team:
# Enable debugging tests with --config=debug test:debug --test_arg=--node_options=--inspect-brk --test_output=streamed --test_strategy=exclusive --test_timeout=9999 --nocache_test_results
Now you can add --config=debug to any bazel test command line. The runtime will pause before executing the program, allowing you to connect a remote debugger.
nodejs_test(name, bootstrap, configuration_env_vars, data, default_env_vars, entry_point, expected_exit_code, install_source_map_support, node_modules, templated_args, templated_args_file)
name(name, mandatory): A unique name for this target.
bootstrap(List of strings): JavaScript modules to be loaded before the entry point. For example, Angular uses this to patch the Jasmine async primitives for zone.js before the first describe.
configuration_env_vars(List of strings): Pass these configuration environment variables to the resulting binary. Chooses a subset of the configuration environment variables (taken from ctx.var), which also includes anything specified via the --define flag. Note, this can lead to different outputs produced by this rule.
data(labels): Runtime dependencies which may be loaded during execution.
default_env_vars(List of strings): Default environment variables that are added to configuration_env_vars.
This is separate from the default of configuration_env_vars so that a user can set configuration_env_vars without losing the defaults that should be set in most cases.
The set of default environment variables is:
DEBUG: rules use this environment variable to turn on debug information in their output artifactsVERBOSE_LOGS: rules use this environment variable to turn on debug output in their logsentry_point(label, mandatory): The script which should be executed first, usually containing a main function.
If the entry JavaScript file belongs to the same package (as the BUILD file), you can simply reference it by its relative name to the package directory:
nodejs_binary(
name = "my_binary",
...
entry_point = ":file.js",
)
You can specify the entry point as a typescript file so long as you also include the ts_library target in data:
ts_library(
name = "main",
srcs = ["main.ts"],
)
nodejs_binary(
name = "bin",
data = [":main"]
entry_point = ":main.ts",
)
The rule will use the corresponding .js output of the ts_library rule as the entry point.
If the entry point target is a rule, it should produce a single JavaScript entry file that will be passed to the nodejs_binary rule. For example:
filegroup(
name = "entry_file",
srcs = ["main.js"],
)
nodejs_binary(
name = "my_binary",
entry_point = ":entry_file",
)
The entry_point can also be a label in another workspace:
nodejs_binary(
name = "history-server",
entry_point = "@npm//:node_modules/history-server/modules/cli.js",
data = ["@npm//history-server"],
)
expected_exit_code(Integer): The expected exit code for the test. Defaults to 0.
install_source_map_support(Boolean): Install the source-map-support package. Enable this to get stack traces that point to original sources, e.g. if the program was written in TypeScript.
node_modules(label): The npm packages which should be available to require() during execution.
This attribute is DEPRECATED. As of version 0.13.0 the recommended approach to npm dependencies is to use fine grained npm dependencies which are setup with the yarn_install or npm_install rules. For example, in targets that used a //:node_modules filegroup,
nodejs_binary(
name = "my_binary",
...
node_modules = "//:node_modules",
)
which specifies all files within the //:node_modules filegroup to be inputs to the my_binary. Using fine grained npm dependencies, my_binary is defined with only the npm dependencies that are needed:
nodejs_binary(
name = "my_binary",
...
data = [
"@npm//foo",
"@npm//bar",
...
],
)
In this case, only the foo and bar npm packages and their transitive deps are includes as inputs to the my_binary target which reduces the time required to setup the runfiles for this target (see https://github.com/bazelbuild/bazel/issues/5153).
The @npm external repository and the fine grained npm package targets are setup using the yarn_install or npm_install rule in your WORKSPACE file:
yarn_install( name = “npm”, package_json = “//:package.json”, yarn_lock = “//:yarn.lock”, )
For other rules such as jasmine_node_test, fine grained npm dependencies are specified in the deps attribute:
jasmine_node_test(
name = "my_test",
...
deps = [
"@npm//jasmine",
"@npm//foo",
"@npm//bar",
...
],
)
templated_args(List of strings): Arguments which are passed to every execution of the program. To pass a node startup option, prepend it with --node_options=, e.g. --node_options=--preserve-symlinks
templated_args_file(Label): If specified, arguments specified in templated_args are instead written to this file, which is then passed as an argument to the program. Arguments prefixed with --node_options= are passed directly to node and not included in the params file.
Runs npm install during workspace setup.
npm_install(name, always_hide_bazel_files, data, dynamic_deps, exclude_packages, included_files, manual_build_file_contents, package_json, package_lock_json, prod_only, quiet, symlink_node_modules, timeout)
name(name, mandatory): A unique name for this repository.
always_hide_bazel_files(Boolean): Always hide Bazel build files such as BUILD and BUILD.bazelby prefixing them with_`.
Defaults to False, in which case Bazel files are not hidden when symlink_node_modules is True. In this case, the rule will report an error when there are Bazel files detected in npm packages.
Reporting the error is desirable as relying on this repository rule to hide these files does not work in the case where a user deletes their node_modules folder and manually re-creates it with yarn or npm outside of Bazel which would restore them. On a subsequent Bazel build, this repository rule does not re-run and the presence of the Bazel files leads to a build failure that looks like the following:
ERROR: /private/var/tmp/_bazel_greg/37b273501bbecefcf5ce4f3afcd7c47a/external/npm/BUILD.bazel:9:1: Label '@npm//:node_modules/rxjs/src/AsyncSubject.ts' crosses boundary of subpackage '@npm//node_modules/rxjs/src' (perhaps you meant to put the colon here: '@npm//node_modules/rxjs/src:AsyncSubject.ts'?)
See https://github.com/bazelbuild/rules_nodejs/issues/802 for more details.
The recommended solution is to use the @bazel/hide-bazel-files utility to hide these files. See https://github.com/bazelbuild/rules_nodejs/blob/master/packages/hide-bazel-files/README.md for installation instructions.
The alternate solution is to set always_hide_bazel_files to True which tell this rule to hide Bazel files even when symlink_node_modules is True. This means you won't need to use @bazel/hide-bazel-files utility but if you manually recreate your node_modules folder via yarn or npm outside of Bazel you may run into the above error.
data(labels): Data files required by this rule.
If symlink_node_modules is True, this attribute is ignored since the dependency manager will run in the package.json location.
dynamic_deps(Dictionary: String -> String): Declare implicit dependencies between npm packages.
In many cases, an npm package doesn't list a dependency on another package, yet still require()s it. One example is plugins, where a tool like rollup can require rollup-plugin-json if the user installed it. Another example is the tsc_wrapped binary in @bazel/typescript which can require tsickle if its installed. Under Bazel, we must declare these dependencies so that they are included as inputs to the program.
Note that the pattern used by many packages, which have plugins in the form pkg-plugin-someplugin, are automatically added as implicit dependencies. Thus for example, rollup will automatically get rollup-plugin-json included in its dependencies without needing to use this attribute.
The keys in the dict are npm package names, and the value may be a particular package, or a prefix ending with *.
For example, dynamic_deps = {"@bazel/typescript": "tsickle", "karma": "my-karma-plugin-*"}
Note, this may sound like “optionalDependencies” but that field in package.json actually means real dependencies which are installed, but failures on installation are ignored.
exclude_packages(List of strings): DEPRECATED. This attribute is no longer used.
included_files(List of strings): List of file extensions to be included in the npm package targets.
For example, [“.js”, “.d.ts”, “.proto”, “.json”, ""].
This option is useful to limit the number of files that are inputs to actions that depend on npm package targets. See https://github.com/bazelbuild/bazel/issues/5153.
If set to an empty list then all files are included in the package targets. If set to a list of extensions, only files with matching extensions are included in the package targets. An empty string in the list is a special string that denotes that files with no extensions such as README should be included in the package targets.
This attribute applies to both the coarse @wksp//:node_modules target as well as the fine grained targets such as @wksp//foo.
manual_build_file_contents(String): Experimental attribute that can be used to override the generated BUILD.bazel file and set its contents manually.
Can be used to work-around a bazel performance issue if the default @wksp//:node_modules target has too many files in it. See https://github.com/bazelbuild/bazel/issues/5153. If you are running into performance issues due to a large node_modules target it is recommended to switch to using fine grained npm dependencies.
package_json(label, mandatory)
package_lock_json(label, mandatory)
prod_only(Boolean): Don't install devDependencies
quiet(Boolean): If stdout and stderr should be printed to the terminal.
symlink_node_modules(Boolean): Turn symlinking of node_modules on
This requires the use of Bazel 0.26.0 and the experimental managed_directories feature.
When true, the package manager will run in the package.json folder and the resulting node_modules folder will be symlinked into the external repository create by this rule.
When false, the package manager will run in the external repository created by this rule and any files other than the package.json file and the lock file that are required for it to run should be listed in the data attribute.
timeout(Integer): Maximum duration of the command “npm install” in seconds (default is 3600 seconds).
The npm_package rule creates a directory containing a publishable npm artifact.
Example:
load("@build_bazel_rules_nodejs//:index.bzl", "npm_package") npm_package( name = "my_package", srcs = ["package.json"], deps = [":my_typescript_lib"], replacements = {"//internal/": "//"}, )
You can use a pair of // BEGIN-INTERNAL ... // END-INTERNAL comments to mark regions of files that should be elided during publishing. For example:
function doThing() { // BEGIN-INTERNAL // This is a secret internal-only comment doInternalOnlyThing(); // END-INTERNAL }
Usage:
npm_package yields three labels. Build the package directory using the default label:
$ bazel build :my_package Target //:my_package up-to-date: bazel-out/fastbuild/bin/my_package $ ls -R bazel-out/fastbuild/bin/my_package
Dry-run of publishing to npm, calling npm pack (it builds the package first if needed):
$ bazel run :my_package.pack INFO: Running command line: bazel-out/fastbuild/bin/my_package.pack my-package-name-1.2.3.tgz $ tar -tzf my-package-name-1.2.3.tgz
Actually publish the package with npm publish (also builds first):
# Check login credentials $ bazel run @nodejs//:npm who # Publishes the package $ bazel run :my_package.publish
You can pass arguments to npm by escaping them from Bazel using a double-hyphen bazel run my_package.publish -- --tag=next
npm_package(name, deps, packages, rename_build_files, replace_with_version, replacements, srcs, vendor_external)
name(name, mandatory): A unique name for this target.
deps(labels): Other targets which produce files that should be included in the package, such as rollup_bundle
packages(labels): Other npm_package rules whose content is copied into this package.
rename_build_files(Boolean): If set BUILD and BUILD.bazel files are prefixed with _ in the npm package. The default is True since npm packages that contain BUILD files don't work with yarn_install and npm_install without a post-install step that deletes or renames them.
replace_with_version(String): If set this value is replaced with the version stamp data. See the section on stamping in the README.
replacements(Dictionary: String -> String): Key-value pairs which are replaced in all the files while building the package.
srcs(labels): Files inside this directory which are simply copied into the package.
vendor_external(List of strings): External workspaces whose contents should be vendored into this workspace. Avoids ‘external/foo’ path segments in the resulting package.
Produces several bundled JavaScript files using Rollup and terser.
Load it with load("@build_bazel_rules_nodejs//:index.bzl", "rollup_bundle")
It performs this work in several separate processes:
The default output of a rollup_bundle rule is the non-debug-minified es5 bundle.
However you can request one of the other outputs with a dot-suffix on the target's name. For example, if your rollup_bundle is named my_rollup_bundle, you can use one of these labels:
To request the ES2015 syntax (e.g. class keyword) without downleveling or minification, use the :my_rollup_bundle.es2015.js label. To request the ES5 downleveled bundle without minification, use the :my_rollup_bundle.js label To request the debug-minified es5 bundle, use the :my_rollup_bundle.min_debug.js label. To request a UMD-bundle, use the :my_rollup_bundle.umd.js label. To request a CommonJS bundle, use the :my_rollup_bundle.cjs.js label.
You can also request an analysis from source-map-explorer by buildng the :my_rollup_bundle.explore.html label. However this is currently broken for rollup_bundle ES5 mode because we use tsc for downleveling and it doesn't compose the resulting sourcemaps with an input sourcemap. See https://github.com/bazelbuild/rules_nodejs/issues/175
For debugging, note that the rollup.config.js and terser.config.json files can be found in the bazel-bin folder next to the resulting bundle.
An example usage can be found in https://github.com/bazelbuild/rules_nodejs/tree/master/internal/rollup/test/rollup
rollup_bundle(name, additional_entry_points, deps, enable_code_splitting, entry_point, global_name, globals, license_banner, node_modules, srcs)
name(name, mandatory): A unique name for this target.
additional_entry_points(List of strings): Additional entry points of the application for code splitting, passed as the input to rollup. These should be a path relative to the workspace root.
When additional_entry_points are specified, rollup_bundle
will split the bundle in multiple entry points and chunks.
There will be a main entry point chunk as well as entry point
chunks for each additional_entry_point. The file names
of these entry points will correspond to the file names
specified in entry_point and additional_entry_points.
There will also be one or more common chunks that are shared
between entry points named chunk-<HASH>.js. The number
of common chunks is variable depending on the code being
bundled.
Entry points and chunks will be outputted to folders:
- <label-name>_chunks_es2015 // es2015
- <label-name>_chunks // es5
- <label-name>_chunks_min // es5 minified
- <label-name>_chunks_min_debug // es5 minified debug
The following files will be outputted that contain the
SystemJS boilerplate to map the entry points to their file
names and load the main entry point:
flavors:
- <label-name>.es2015.js // es2015 with EcmaScript modules
- <label-name>.js // es5 syntax with CJS modules
- <label-name>.min.js // es5 minified
- <label-name>.min_debug.js // es5 minified debug
NOTE: additional_entry_points MUST be in the same folder or deeper than
the main entry_point for the SystemJS boilerplate/entry point to
be valid. For example, if the main entry_point is
`src/main` then all additional_entry_points must be under
`src/**` such as `src/bar` or `src/foo/bar`. Alternate
additional_entry_points configurations are valid but the
SystemJS boilerplate/entry point files will not be usable and
it is up to the user in these cases to handle the SystemJS
boilerplate manually.
It is sufficient to load one of these SystemJS boilerplate/entry point
files as a script in your HTML to load your application
deps(labels): Other rules that produce JavaScript outputs, such as ts_library.
enable_code_splitting(Boolean): If True rollup will automatically determine entry points from the source code. The rollup output format will be ‘esm’ and rollup will create entry points based on ES6 import statements. See https://rollupjs.org/guide/en#code-splitting
Code splitting is always enabled when additional_entry_points is
non-empty.
All automatic entry points will be named chunk-<HASH>.js.
entry_point(label, mandatory): The starting point of the application, passed as the --input flag to rollup.
If the entry JavaScript file belongs to the same package (as the BUILD file),
you can simply reference it by its relative name to the package directory:
```
rollup_bundle(
name = "bundle",
entry_point = ":main.js",
)
```
You can specify the entry point as a typescript file so long as you also include
the ts_library target in deps:
```
ts_library(
name = "main",
srcs = ["main.ts"],
)
rollup_bundle(
name = "bundle",
deps = [":main"]
entry_point = ":main.ts",
)
```
The rule will use the corresponding `.js` output of the ts_library rule as the entry point.
If the entry point target is a rule, it should produce a single JavaScript entry file that will be passed to the nodejs_binary rule.
For example:
```
filegroup(
name = "entry_file",
srcs = ["main.js"],
)
rollup_bundle(
name = "bundle",
entry_point = ":entry_file",
)
```
global_name(String): A name given to this package when referenced as a global variable. This name appears in the bundle module incantation at the beginning of the file, and governs the global symbol added to the global context (e.g. window) as a side- effect of loading the UMD/IIFE JS bundle.
Rollup doc: "The variable name, representing your iife/umd bundle, by which other scripts on the same page can access it."
This is passed to the `output.name` setting in Rollup.
globals(Dictionary: String -> String): A dict of symbols that reference external scripts. The keys are variable names that appear in the program, and the values are the symbol to reference at runtime in a global context (UMD bundles). For example, a program referencing @angular/core should use ng.core as the global reference, so Angular users should include the mapping "@angular/core":"ng.core" in the globals.
license_banner(label): A .txt file passed to the banner config option of rollup. The contents of the file will be copied to the top of the resulting bundles. Note that you can replace a version placeholder in the license file, by using the special version 0.0.0-PLACEHOLDER. See the section on stamping in the README.
node_modules(label): Dependencies from npm that provide some modules that must be resolved by rollup.
This attribute is DEPRECATED. As of version 0.13.0 the recommended approach
to npm dependencies is to use fine grained npm dependencies which are setup
with the `yarn_install` or `npm_install` rules. For example, in a rollup_bundle
target that used the `node_modules` attribute,
```
rollup_bundle(
name = "bundle",
...
node_modules = "//:node_modules",
)
```
which specifies all files within the `//:node_modules` filegroup
to be inputs to the `bundle`. Using fine grained npm dependencies,
`bundle` is defined with only the npm dependencies that are
needed:
```
rollup_bundle(
name = "bundle",
...
deps = [
"@npm//foo",
"@npm//bar",
...
],
)
```
In this case, only the `foo` and `bar` npm packages and their
transitive deps are includes as inputs to the `bundle` target
which reduces the time required to setup the runfiles for this
target (see https://github.com/bazelbuild/bazel/issues/5153).
The @npm external repository and the fine grained npm package
targets are setup using the `yarn_install` or `npm_install` rule
in your WORKSPACE file:
yarn_install(
name = "npm",
package_json = "//:package.json",
yarn_lock = "//:yarn.lock",
)
srcs(labels): JavaScript source files from the workspace. These can use ES2015 syntax and ES Modules (import/export)
Runs yarn install during workspace setup.
yarn_install(name, always_hide_bazel_files, data, dynamic_deps, exclude_packages, frozen_lockfile, included_files, manual_build_file_contents, network_timeout, package_json, prod_only, quiet, symlink_node_modules, timeout, use_global_yarn_cache, yarn_lock)
name(name, mandatory): A unique name for this repository.
always_hide_bazel_files(Boolean): Always hide Bazel build files such as BUILD and BUILD.bazelby prefixing them with_`.
Defaults to False, in which case Bazel files are not hidden when symlink_node_modules is True. In this case, the rule will report an error when there are Bazel files detected in npm packages.
Reporting the error is desirable as relying on this repository rule to hide these files does not work in the case where a user deletes their node_modules folder and manually re-creates it with yarn or npm outside of Bazel which would restore them. On a subsequent Bazel build, this repository rule does not re-run and the presence of the Bazel files leads to a build failure that looks like the following:
ERROR: /private/var/tmp/_bazel_greg/37b273501bbecefcf5ce4f3afcd7c47a/external/npm/BUILD.bazel:9:1: Label '@npm//:node_modules/rxjs/src/AsyncSubject.ts' crosses boundary of subpackage '@npm//node_modules/rxjs/src' (perhaps you meant to put the colon here: '@npm//node_modules/rxjs/src:AsyncSubject.ts'?)
See https://github.com/bazelbuild/rules_nodejs/issues/802 for more details.
The recommended solution is to use the @bazel/hide-bazel-files utility to hide these files. See https://github.com/bazelbuild/rules_nodejs/blob/master/packages/hide-bazel-files/README.md for installation instructions.
The alternate solution is to set always_hide_bazel_files to True which tell this rule to hide Bazel files even when symlink_node_modules is True. This means you won't need to use @bazel/hide-bazel-files utility but if you manually recreate your node_modules folder via yarn or npm outside of Bazel you may run into the above error.
data(labels): Data files required by this rule.
If symlink_node_modules is True, this attribute is ignored since the dependency manager will run in the package.json location.
dynamic_deps(Dictionary: String -> String): Declare implicit dependencies between npm packages.
In many cases, an npm package doesn't list a dependency on another package, yet still require()s it. One example is plugins, where a tool like rollup can require rollup-plugin-json if the user installed it. Another example is the tsc_wrapped binary in @bazel/typescript which can require tsickle if its installed. Under Bazel, we must declare these dependencies so that they are included as inputs to the program.
Note that the pattern used by many packages, which have plugins in the form pkg-plugin-someplugin, are automatically added as implicit dependencies. Thus for example, rollup will automatically get rollup-plugin-json included in its dependencies without needing to use this attribute.
The keys in the dict are npm package names, and the value may be a particular package, or a prefix ending with *.
For example, dynamic_deps = {"@bazel/typescript": "tsickle", "karma": "my-karma-plugin-*"}
Note, this may sound like “optionalDependencies” but that field in package.json actually means real dependencies which are installed, but failures on installation are ignored.
exclude_packages(List of strings): DEPRECATED. This attribute is no longer used.
frozen_lockfile(Boolean): Passes the --frozen-lockfile flag to prevent updating yarn.lock.
Note that enabling this option will require that you run yarn outside of Bazel when making changes to package.json.
included_files(List of strings): List of file extensions to be included in the npm package targets.
For example, [“.js”, “.d.ts”, “.proto”, “.json”, ""].
This option is useful to limit the number of files that are inputs to actions that depend on npm package targets. See https://github.com/bazelbuild/bazel/issues/5153.
If set to an empty list then all files are included in the package targets. If set to a list of extensions, only files with matching extensions are included in the package targets. An empty string in the list is a special string that denotes that files with no extensions such as README should be included in the package targets.
This attribute applies to both the coarse @wksp//:node_modules target as well as the fine grained targets such as @wksp//foo.
manual_build_file_contents(String): Experimental attribute that can be used to override the generated BUILD.bazel file and set its contents manually.
Can be used to work-around a bazel performance issue if the default @wksp//:node_modules target has too many files in it. See https://github.com/bazelbuild/bazel/issues/5153. If you are running into performance issues due to a large node_modules target it is recommended to switch to using fine grained npm dependencies.
network_timeout(Integer): Maximum duration of a network request made by yarn in seconds (default is 300 seconds).
package_json(label, mandatory)
prod_only(Boolean): Don't install devDependencies
quiet(Boolean): If stdout and stderr should be printed to the terminal.
symlink_node_modules(Boolean): Turn symlinking of node_modules on
This requires the use of Bazel 0.26.0 and the experimental managed_directories feature.
When true, the package manager will run in the package.json folder and the resulting node_modules folder will be symlinked into the external repository create by this rule.
When false, the package manager will run in the external repository created by this rule and any files other than the package.json file and the lock file that are required for it to run should be listed in the data attribute.
timeout(Integer): Maximum duration of the command “yarn install” in seconds (default is 3600 seconds).
use_global_yarn_cache(Boolean): Use the global yarn cache on the system.
The cache lets you avoid downloading packages multiple times. However, it can introduce non-hermeticity, and the yarn cache can have bugs. Disabling this attribute causes every run of yarn to have a unique cache_directory.
yarn_lock(label, mandatory)
Verify the users Bazel version is at least the given one.
This should be called from the WORKSPACE file so that the build fails as early as possible. For example:
# in WORKSPACE:
load("@build_bazel_rules_nodejs//:index.bzl", "check_bazel_version")
check_bazel_version("0.26.0")
check_bazel_version(minimum_bazel_version, message)
minimum_bazel_versiona string indicating the minimum version
messageoptional string to print to your users, could be used to help them update
Defaults to ""
Run an arbitrary npm package binary (anything under node_modules/.bin/*) under Bazel.
It must produce outputs. If you just want to run a program with bazel run, use the nodejs_binary rule.
This is like a genrule() except that it runs our launcher script that first links the node_modules tree before running the program.
This is a great candidate to wrap with a macro, as documented: https://docs.bazel.build/versions/master/skylark/macros.html#full-example
npm_package_bin(tool, package, package_bin, data, outs, args, output_dir, kwargs)
toola label for a binary to run, like @npm//terser/bin:terser. This is the longer form of package/package_bin. Note that you can also refer to a binary in your local workspace.
Defaults to None
packagean npm package whose binary to run, like “terser”. Assumes your node_modules are installed in a workspace called “npm”
Defaults to None
package_binthe “bin” entry from package that should be run. By default package_bin is the same string as package
Defaults to None
datasimilar to genrule.srcs may also include targets that produce or reference npm packages which are needed by the tool
Defaults to []
outssimilar to genrule.outs
Defaults to []
argsCommand-line arguments to the tool.
Subject to 'Make variable' substitution. Can use $(location) expansion. See https://docs.bazel.build/versions/master/be/make-variables.html You may also refer to the location of the output_dir with the special `$@` replacement, like genrule.
Defaults to []
output_dirset to True if you want the output to be a directory Exactly one of outs, output_dir may be used. If you output a directory, there can only be one output, which will be named the same as the target.
Defaults to False
kwargs