@aspect_rules_js//contrib/nextjs:defs.bzl
Utilities for building Next.js applications with Bazel and rules_js.
All invocations of Next.js are done through a next_js_binary target passed into the macros.
This is normally generated once alongside the package.json containing the next dependency:
load("@npm//:next/package_json.bzl", next_bin = "bin")
next_bin.next_binary(
name = "next_js_binary",
visibility = ["//visibility:public"],
)
The next binary is then passed into the macros, for example:
nextjs_build(
name = "next",
config = "next.config.mjs",
srcs = glob(["src/**"]),
next_js_binary = "//:next_js_binary",
)
Macros
There are two sets of macros for building Next.js applications: standard and standalone.
Standard
nextjs(): wrap the build+dev+start targetsnextjs_build(): the Next.js build commandnextjs_dev(): the Next.js dev commandnextjs_start(): the Next.js start command,
accepting a Next.js build artifact to start
Standalone
nextjs_standalone_build(): the Next.js build command,
configured for a standalone application within bazelnextjs_standalone_server(): constructs a standalone Next.js serverjs_binaryfollowing the
standalone directory structure guidelines
Functions & Macros
nextjsGenerates Next.js build, dev & start targets.
{name} - a Next.js production bundle
{name}.dev - a Next.js devserver
{name}.start - a Next.js prodserver
Use this macro in the BUILD file at the root of a next app where the next.config.mjs
file is located.
For example, a target such as //app:next in app/BUILD.bazel
next(
name = "next",
config = "next.config.mjs",
srcs = glob(["src/**"]),
data = [
"//:node_modules/next",
"//:node_modules/react-dom",
"//:node_modules/react",
"package.json",
],
next_js_binary = "//:next_js_binary",
)
will create the targets:
//app:next
//app:next.dev
//app:next.start
To build the above next app, equivalent to running next build outside Bazel:
bazel build //app:next
To run the development server in watch mode with
ibazel, equivalent to running
next dev outside Bazel:
ibazel run //app:next.dev
To run the production server in watch mode with
ibazel, equivalent to running
next start outside Bazel:
ibazel run //app:next.start
Parameters
*name | the name of the build target |
*srcs | Source files to include in build & dev targets. |
*next_js_binary | The next Typically this is a js_binary target created using See main docstring above for example usage. |
config | the Next.js config file. Typically Default: "next.config.mjs" |
data | Data files to include in all targets. Default: [] |
serve_data | Data files to include in devserver targets Default: [] |
kwargs | Other attributes passed to all targets such as |
nextjs_buildBuild the Next.js production artifact.
See https://nextjs.org/docs/pages/api-reference/cli/next#build
Parameters
*name | the name of the build target |
*config | the Next.js config file |
*srcs | the sources to include in the build, including any transitive deps |
*next_js_binary | The next Typically this is a js_binary target created using See main docstring above for example usage. |
data | the data files to include in the build Default: [] |
kwargs | Other attributes passed to all targets such as |
nextjs_startRun the Next.js production server for an app.
See https://nextjs.org/docs/pages/api-reference/cli/next#next-start-options
Parameters
*name | the name of the build target |
*config | the Next.js config file |
*app | the pre-compiled Next.js application, typically the output of |
*next_js_binary | The next Typically this is a js_binary target created using See main docstring above for example usage. |
data | additional server data Default: [] |
kwargs | Other attributes passed to all targets such as |
nextjs_devRun the Next.js development server.
See https://nextjs.org/docs/pages/api-reference/cli/next#next-dev-options
Parameters
*name | the name of the build target |
*config | the Next.js config file |
*srcs | the sources to include in the build, including any transitive deps |
*data | additional devserver runtime data |
*next_js_binary | The next Typically this is a js_binary target created using See main docstring above for example usage. |
kwargs | Other attributes passed to all targets such as |
nextjs_standalone_buildCompile a standalone Next.js application.
NOTE: a next.config.mjs is generated, wrapping the passed config, to overcome Next.js limitation with bazel,
rules_js and pnpm (with hoist=false, as required by rules_js).
Due to the generated next.config.mjs file the nextjs_standalone_build(config) must have a unique name
or file path that does not conflict with standard Next.js config files.
Issues worked around by the generated config include:
Parameters
*name | the name of the build target |
*config | the Next.js config file |
*srcs | the sources to include in the build, including any transitive deps |
*next_js_binary | the Next.js binary to use for building |
data | the data files to include in the build Default: [] |
kwargs | Other attributes passed to all targets such as |
nextjs_standalone_serverConfigures the output of a standalone Next.js application to be a standalone server binary.
See the Next.js standalone server documentation
for details on the standalone server directory structure.
This function is normally used in conjunction with nextjs_standalone_build to create a standalone
Next.js application. The standalone server is a js_binary target that can be run with bazel run
or deployed in a container image etc.
Parameters
*name | the name of the binary target |
*app | the standalone app directory, typically the output of |
pkg | the directory server.js is in within the standalone/ directory. This is normally the application path relative to the pnpm-lock.yaml. Default: native.package_name() (for a pnpm-lock.yaml in the root of the workspace) Default: None |
data | runtime data required to run the standalone server. Normally requires Default: [] |
kwargs | additional |
@aspect_rules_js//js:defs.bzl
Rules for running JavaScript programs
Functions & Macros
js_binaryParameters
kwargs |
js_testParameters
kwargs |
js_run_devserverRuns a devserver via binary target or command.
A simple http-server, for example, can be setup as follows,
load("@aspect_rules_js//js:defs.bzl", "js_run_devserver")
load("@npm//:http-server/package_json.bzl", http_server_bin = "bin")
http_server_bin.http_server_binary(
name = "http_server",
)
js_run_devserver(
name = "serve",
args = ["."],
data = ["index.html"],
tool = ":http_server",
)
A Next.js devserver can be setup as follows,
js_run_devserver(
name = "dev",
args = ["dev"],
command = "./node_modules/.bin/next",
data = [
"next.config.js",
"package.json",
":node_modules/next",
":node_modules/react",
":node_modules/react-dom",
":node_modules/typescript",
"//pages",
"//public",
"//styles",
],
)
where the ./node_modules/.bin/next bin entry of Next.js is configured in
npm_translate_lock as such,
npm_translate_lock(
name = "npm",
bins = {
# derived from "bin" attribute in node_modules/next/package.json
"next": {
"next": "./dist/bin/next",
},
},
pnpm_lock = "//:pnpm-lock.yaml",
)
and run in watch mode using ibazel with
ibazel run //:dev.
The devserver specified by either tool or command is run in a custom sandbox that is more
compatible with devserver watch modes in Node.js tools such as Webpack and Next.js.
The custom sandbox is populated with the default outputs of all targets in data
as well as transitive sources & npm links.
As an optimization, package store files are explicitly excluded from the sandbox since the npm
links will point to the package store in the execroot and Node.js will follow those links as it
does within the execroot. As a result, rules_js npm package link targets such as
//:node_modules/next are handled efficiently. Since these targets are symlinks in the output
tree, they are recreated as symlinks in the custom sandbox and do not incur a full copy of the
underlying npm packages.
Supports running with ibazel.
Only data files that change on incremental builds are synchronized when running with ibazel.
Note that the use of alias targets is not supported by ibazel: https://github.com/bazelbuild/bazel-watcher/issues/100
Parameters
*name | A unique name for this target. |
tool | The devserver binary target to run. Only one of Default: None |
command | The devserver command to run. For example, this could be the bin entry of an npm package that is included Using the bin entry of next, for example, resolves issues with Next.js and React Only one of Default: None |
grant_sandbox_write_permissions | If set, write permissions is set on all files copied to the custom sandbox. This can be useful to support some devservers such as Next.js which may, under some See https://github.com/aspect-build/rules_js/issues/935 for more context. Default: False |
use_execroot_entry_point | Use the Using the entry point script that is in the execroot output tree means that there will be no conflicting When True, the Default: True |
allow_execroot_entry_point_with_no_copy_data_to_bin | Turn off validation that the See Default: False |
kwargs | All other args from
See https://docs.aspect.build/rules/aspect_rules_js/docs/js_binary |
js_run_binaryWrapper around @bazel_lib run_binary that adds convenience attributes for using a js_binary tool.
This rule does not require Bash native.genrule.
The following environment variables are made available to the Node.js runtime based on available Bazel Make variables:
- BAZEL_BINDIR: the bazel bin directory; equivalent to the
$(BINDIR)Make variable of thejs_run_binarytarget - BAZEL_COMPILATION_MODE: One of
fastbuild,dbg, oroptas set by--compilation_mode; equivalent to$(COMPILATION_MODE)Make variable of thejs_run_binarytarget - BAZEL_TARGET_CPU: the target cpu architecture; equivalent to
$(TARGET_CPU)Make variable of thejs_run_binarytarget
The following environment variables are made available to the Node.js runtime based on the rule context:
- BAZEL_BUILD_FILE_PATH: the path to the BUILD file of the bazel target being run; equivalent to
ctx.build_file_pathof thejs_run_binarytarget's rule context - BAZEL_PACKAGE: the package of the bazel target being run; equivalent to
ctx.label.packageof thejs_run_binarytarget's rule context - BAZEL_TARGET_NAME: the full label of the bazel target being run; a stringified version of
ctx.labelof thejs_run_binarytarget's rule context - BAZEL_TARGET: the name of the bazel target being run; equivalent to
ctx.label.nameof thejs_run_binarytarget's rule context - BAZEL_WORKSPACE: the bazel repository name; equivalent to
ctx.workspace_nameof thejs_run_binarytarget's rule context
Parameters
*name | Target name |
*tool | The tool to run in the action. Should be a |
env | Environment variables of the action. Subject to Default: {} |
srcs | Additional inputs of the action. These labels are available for Default: [] |
outs | Output files generated by the action. These labels are available for Default: [] |
out_dirs | Output directories generated by the action. These labels are not available for Default: [] |
args | Command line arguments of the binary. Subject to Default: [] |
chdir | Working directory to run the build action in. This overrides the chdir value if set on the By default, To run in the directory containing the js_run_binary in the output tree, use WARNING: this will affect other paths passed to the program, either as arguments or in configuration files, You may need Default: None |
stdout | Output file to capture the stdout of the binary. This can later be used as an input to another target subject to the same semantics as If the binary creates outputs and these are declared, they must still be created. Default: None |
stderr | Output file to capture the stderr of the binary to. This can later be used as an input to another target subject to the same semantics as If the binary creates outputs and these are declared, they must still be created. Default: None |
exit_code_out | Output file to capture the exit code of the binary to. This can later be used as an input to another target subject to the same semantics as If the binary creates outputs and these are declared, they must still be created. Default: None |
silent_on_success | produce no output on stdout nor stderr when program exits with status code 0. This makes node binaries match the expected bazel paradigm. Default: True |
use_execroot_entry_point | Use the Runfiles of Using the entry point script that is in the execroot output tree means that there will be no conflicting When True, the Default: True |
copy_srcs_to_bin | When True, all srcs files are copied to the output tree that are not already there. Default: True |
include_sources | see Default: True |
include_types | see Default: False |
include_transitive_sources | see Default: True |
include_transitive_types | see Default: False |
include_npm_sources | see Default: True |
log_level | Set the logging level of the This overrides the log level set on the Default: None |
mnemonic | A one-word description of the action, for example, CppCompile or GoLink. Default: "JsRunBinary" |
progress_message | Progress message to show to the user during the build, for example, Default: None |
execution_requirements | Information for scheduling the action. For example,
See https://docs.bazel.build/versions/main/be/common-definitions.html#common.tags for useful keys. Default: None |
stamp | Whether to include build status files as inputs to the tool. Possible values:
Default value is When stamping is enabled, an additional two environment variables will be set for the action: These files can be read and parsed by the action, for example to pass some values to a bundler. Default: 0 |
patch_node_fs | Patch the to Node.js When enabled, When disabled, node programs can leave the execroot, runfiles and sandbox by following symlinks Default: True |
allow_execroot_entry_point_with_no_copy_data_to_bin | Turn off validation that the See Default: False |
use_default_shell_env | Passed to the underlying ctx.actions.run. May introduce non-determinism when True; use with care! Refer to https://bazel.build/rules/lib/builtins/actions#run for more details. Default: False |
kwargs | Additional arguments |
Rules
js_libraryA library of JavaScript sources. Provides JsInfo, the primary provider used in rules_js
and derivative rule sets.
Declaration files are handled separately from sources since they are generally not needed at
runtime and build rules, such as ts_project, are optimal in their build graph if they only depend
on types from deps since these they don't need the JavaScript source files from deps to
typecheck.
Linked npm dependences are also handled separately from sources since not all rules require them and it
is optimal for these rules to not depend on them in the build graph.
NB: js_library copies all source files to the output tree before providing them in JsInfo. See
https://github.com/aspect-build/rules_js/tree/dbb5af0d2a9a2bb50e4cf4a96dbc582b27567155/docs#javascript
for more context on why we do this.
| Attribute | Type | Description |
|---|---|---|
*name | name | A unique name for this target. |
srcs | list of labels | Source files that are included in this library. This includes all your checked-in code and any generated source files. The transitive npm dependencies, transitive sources & runfiles of targets in the Source files that are JSON files, declaration files or directory artifacts will be automatically provided as Default: [] |
types | list of labels | Same as For example, a js_library with only Default: [] |
deps | list of labels | Dependencies of this target. This may include other js_library targets or other targets that provide JsInfo The transitive npm dependencies, transitive sources & runfiles of targets in the If this list contains linked npm packages, npm package store targets or other targets that provide NB: Linked npm package targets that are "dev" dependencies do not forward their underlying Default: [] |
data | list of labels | Runtime dependencies to include in binaries/tests that depend on this target. The transitive npm dependencies, transitive sources, default outputs and runfiles of targets in the If this list contains linked npm packages, npm package store targets or other targets that provide NB: Linked npm package targets that are "dev" dependencies do not forward their underlying Default: [] |
no_copy_to_bin | list of labels | List of files to not copy to the Bazel output tree when This is useful for exceptional cases where a Default: [] |
copy_data_to_bin | boolean | When True, Default: True |
js_info_filesGathers files from the JsInfo providers from targets in srcs and provides them as default outputs.
This helper rule is used by the js_run_binary macro.
| Attribute | Type | Description |
|---|---|---|
*name | name | A unique name for this target. |
srcs | list of labels | List of targets to gather files from. Default: [] |
include_sources | boolean | When True, Default: True |
include_transitive_sources | boolean | When True, Default: True |
include_types | boolean | When True, Defaults to False since types are generally not needed at runtime and introducing them could slow down developer round trip NB: These are types from direct Default: False |
include_transitive_types | boolean | When True, Defaults to False since types are generally not needed at runtime and introducing them could slow down developer round trip Default: False |
include_npm_sources | boolean | When True, files in
Default: True |
js_image_layerCreate container image layers from js_binary targets.
By design, js_image_layer doesn't have any preference over which rule assembles the container image.
This means the downstream rule (oci_image from rules_oci
or container_image from rules_docker) must
set a proper workdir and cmd to for the container work.
A proper cmd usually looks like /[ js_image_layer 'root' ]/[ package name of js_image_layer 'binary' target ]/[ name of js_image_layer 'binary' target ],
unless you have a custom launcher script that invokes the entry_point of the js_binary in a different path.
On the other hand, workdir has to be set to the "runfiles tree root" which would be exactly cmd but with .runfiles/[ name of the workspace ] suffix.
When using bzlmod then name of the local workspace is always _main. If workdir is not set correctly, some attributes such as chdir might not work properly.
js_image_layer creates up to 5 layers depending on what files are included in the runfiles of the provided
binary target.
nodelayer contains the Node.js toolchainpackage_store_3player contains all 3p npm deps in thenode_modules/.aspect_rules_jspackage storepackage_store_1player contains all 1p npm deps in thenode_modules/.aspect_rules_jspackage storenode_moduleslayer contains allnode_modules/*symlinks which point into the package storeapplayer contains all files that don't fall into any of the above layers
If no files are found in the runfiles of the binary target for one of the layers above, that
layer is not generated. All generated layer tarballs are provided as DefaultInfo files.
The rules_js
node_modules/.aspect_rules_jspackage store follows the same pattern as the pnpm
node_modules/.pnpmvirtual store. For more information see https://pnpm.io/symlinked-node-modules-structure.
js_image_layer also provides an OutputGroupInfo with outputs for each of the layers above which
can be used to reference an individual layer with using filegroup with output_group. For example,
js_image_layer( name = "layers", binary = ":bin", root = "/app", ) filegroup( name = "app_tar", srcs = [":layers"], output_group = "app", )
WARNING: The structure of the generated layers are not subject to semver guarantees and may change without a notice.
However, it is guaranteed to work when all generated layers are provided together in the order specified above.
js_image_layer supports transitioning to specific platform to allow building multi-platform container images.
A partial example using rules_oci with transition to linux/amd64 platform.
load("@aspect_rules_js//js:defs.bzl", "js_binary", "js_image_layer") load("@rules_oci//oci:defs.bzl", "oci_image") js_binary( name = "bin", entry_point = "main.js", ) platform( name = "amd64_linux", constraint_values = [ "@platforms//os:linux", "@platforms//cpu:x86_64", ], ) js_image_layer( name = "layers", binary = ":bin", platform = ":amd64_linux", root = "/app", ) oci_image( name = "image", cmd = ["/app/bin"], entrypoint = ["bash"], tars = [ ":layers" ], workdir = "/app/bin.runfiles/_main", )
A partial example using rules_oci to create multi-platform images.
load("@aspect_rules_js//js:defs.bzl", "js_binary", "js_image_layer") load("@rules_oci//oci:defs.bzl", "oci_image", "oci_image_index") js_binary( name = "bin", entry_point = "main.js", ) [ platform( name = "linux_{}".format(arch), constraint_values = [ "@platforms//os:linux", "@platforms//cpu:{}".format(arch if arch != "amd64" else "x86_64"), ], ) js_image_layer( name = "{}_layers".format(arch), binary = ":bin", platform = ":linux_{arch}", root = "/app", ) oci_image( name = "{}_image".format(arch), cmd = ["/app/bin"], entrypoint = ["bash"], tars = [ ":{}_layers".format(arch) ], workdir = "/app/bin.runfiles/_main", ) for arch in ["amd64", "arm64"] ] oci_image_index( name = "image", images = [ ":arm64_image", ":amd64_image" ] )
Performance
For better performance, it is recommended to split the large parts of a js_binary to have a separate layer.
The matching order for layer groups is as follows:
layer_groupsare checked in order first- If no match is found for
layer_groups, thedefault layer groupsare checked. - Any remaining files are placed into the app layer.
The default layer groups are as follows and always created.
{
"node": "/js/private/node-patches/|/bin/nodejs/",
"package_store_1p": "\.aspect_rules_js/.*@0\.0\.0/node_modules",
"package_store_3p": "\.aspect_rules_js/.*/node_modules",
"node_modules": "/node_modules/",
"app": "", # empty means just match anything.
}
| Attribute | Type | Description |
|---|---|---|
*name | name | A unique name for this target. |
*binary | label | Label to an js_binary target |
root | string | Path where the files from js_binary will reside in. eg: /apps/app1 or /app Default: "" |
owner | string | Owner of the entries, in Default: "0:0" |
directory_mode | string | Mode of the directories, in Default: "0755" |
file_mode | string | Mode of the files, in Default: "0555" |
compression | string | Compression algorithm. See https://github.com/bazel-contrib/bazel-lib/blob/bdc6ade0ba1ebe88d822bcdf4d4aaa2ce7e2cd37/lib/private/tar.bzl#L29-L39 Default: "gzip" |
platform | label | Platform to transition. Default: None |
preserve_symlinks | string | Preserve symlinks for entries matching the pattern. Default: ".*/node_modules/.*" |
layer_groups | dictionary: String → String | Layer groups to create. Default: {} |
@aspect_rules_js//npm:defs.bzl
Rules for fetching and linking npm dependencies and packaging and linking first-party deps
Functions & Macros
npm_packageA macro that packages sources into a directory (a tree artifact) and provides an NpmPackageInfo.
This target can be used as the src attribute to npm_link_package.
With publishable = True the macro also produces a target [name].publish, that can be run to publish to an npm registry.
Under the hood, this target runs npm publish. You can pass arguments to npm by escaping them from Bazel using a double-hyphen,
for example: bazel run //path/to:my_package.publish -- --tag=next
Files and directories can be arranged as needed in the output directory using
the root_paths, include_srcs_patterns, exclude_srcs_patterns and replace_prefixes attributes.
Filters and transformations are applied in the following order:
-
include_external_repositories -
include_srcs_packages -
exclude_srcs_packages -
root_paths -
include_srcs_patterns -
exclude_srcs_patterns -
replace_prefixes
For more information each filters / transformations applied, see
the documentation for the specific filter / transformation attribute.
Glob patterns are supported. Standard wildcards (globbing patterns) plus the ** doublestar (aka. super-asterisk)
are supported with the underlying globbing library, https://github.com/bmatcuk/doublestar. This is the same
globbing library used by gazelle. See https://github.com/bmatcuk/doublestar#patterns
for more information on supported globbing patterns.
npm_package makes use of copy_to_directory
(https://docs.aspect.build/rules/bazel_lib/docs/copy_to_directory) under the hood,
adopting its API and its copy action using composition. However, unlike copy_to_directory,
npm_package includes direct and transitive sources and types files from JsInfo providers in srcs
by default. The behavior of including sources and types from JsInfo can be configured
using the include_sources, include_transitive_sources, include_types, include_transitive_types.
The two include*_types options may cause type-check actions to run, which slows down your
development round-trip.
As of rules_js 2.0, the recommended solution for avoiding eager type-checking when linking
1p deps is to link js_library or any JsInfo producing targets directly without the
indirection of going through an npm_package target (see https://github.com/aspect-build/rules_js/pull/1646
for more details).
npm_package can also include npm packages sources and default runfiles from srcs which copy_to_directory does not.
These behaviors can be configured with the include_npm_sourfes and include_runfiles attributes
respectively.
The default include_srcs_packages, [".", "./**"], prevents files from outside of the target's
package and subpackages from being included.
The default exclude_srcs_patterns, of ["node_modules/**", "**/node_modules/**"], prevents
node_modules files from being included.
To stamp the current git tag as the "version" in the package.json file, see
stamped_package_json
Parameters
*name | Unique name for this target. |
srcs | Files and/or directories or targets that provide Default: [] |
data | Runtime / linktime npm dependencies of this npm package.
Gathered Default: [] |
args | Arguments that are passed down to Default: [] |
out | Path of the output directory, relative to this package. Default: None |
package | The package name. If set, should match the If set, the package name set here will be used for linking if a npm_link_package does not specify a package name. A If unset, a npm_link_package that references this npm_package must define the package name must be for linking. Default: "" |
version | The package version. If set, should match the If set, a npm_link_package may omit the package version and the package version set here will be used for linking. A If unset, a npm_link_package that references this npm_package must define the package version must be for linking. Default: "0.0.0" |
root_paths | List of paths (with glob support) that are roots in the output directory. If any parent directory of a file being copied matches one of the root paths Matching is done on the parent directory of the output file path so a trailing '**' glob patterm Forward slashes ( A Defaults to Globs are supported (see rule docstring above). Default: ["."] |
include_external_repositories | List of external repository names (with glob support) to include in the output directory. Files from external repositories are only copied into the output directory if When copied from an external repository, the file path in the output directory For example, the following copies
Files that come from matching external are subject to subsequent filters and Globs are supported (see rule docstring above). Default: [] |
include_srcs_packages | List of Bazel packages (with glob support) to include in output directory. Files in srcs are only copied to the output directory if Forward slashes ( Defaults to ["./**"] which includes sources target's package and subpackages. Files that have matching Bazel packages are subject to subsequent filters and Globs are supported (see rule docstring above). Default: ["./**"] |
exclude_srcs_packages | List of Bazel packages (with glob support) to exclude from output directory. Files in srcs are not copied to the output directory if Forward slashes ( Defaults to ["/node_modules/"] which excludes all node_modules folders Files that have do not have matching Bazel packages are subject to subsequent Globs are supported (see rule docstring above). Default: [] |
include_srcs_patterns | List of paths (with glob support) to include in output directory. Files in srcs are only copied to the output directory if their output Forward slashes ( Defaults to Files that have matching output directory paths are subject to subsequent Globs are supported (see rule docstring above). Default: ["**"] |
exclude_srcs_patterns | List of paths (with glob support) to exclude from output directory. Files in srcs are not copied to the output directory if their output Forward slashes ( Files that do not have matching output directory paths are subject to subsequent Globs are supported (see rule docstring above). Default: ["**/node_modules/**"] |
replace_prefixes | Map of paths prefixes (with glob support) to replace in the output directory path when copying files. If the output directory path for a file starts with or fully matches a Forward slashes ( Replace prefix transformation are the final step in the list of filters and transformations. Globs are supported (see rule docstring above). Default: {} |
allow_overwrites | If True, allow files to be overwritten if the same output file is copied to twice. The order of srcs matters as the last copy of a particular file will win when overwriting. Default: False |
include_sources | When True, Default: True |
include_types | When True, Default: True |
include_transitive_sources | When True, Default: True |
include_transitive_types | When True, Default: True |
include_npm_sources | When True, Default: False |
include_runfiles | When True, default runfiles from This may be needed in a few cases:
NB: The default value will be flipped to False in the next major release as runfiles are not needed in the general case Default: False |
hardlink | Controls when to use hardlinks to files instead of making copies. Creating hardlinks is much faster than making copies of files with the caveat that Since Bazel removes write permissions on files in the output tree after an action completes,
Default: "auto" |
publishable | When True, enable generation of Default: False |
verbose | If true, prints out verbose logs to stdout Default: False |
kwargs | Additional attributes such as |
npm_link_package"Create a package store entry with the provided source and link to node_modules.
This is a convenience macro that creates both an npm_package_store and a a single npm_link_package_store
to link the package into node_modules/<package>.
A {name}/dir filegroup is also generated that refers to a directory artifact can be used to access
the package directory for creating entry points or accessing files in the package.
Parameters
*name | The name of the link target to create if |
*src | the target to link; may only to be specified when linking in the root package |
deps | list of npm_package_store; may only to be specified when linking in the root package Default: {} |
auto_manual | whether or not to automatically add a manual tag to the generated targets Default: True |
visibility | the visibility of the link target Default: ["//visibility:public"] |
kwargs | see attributes of npm_package_store rule |
stamped_package_jsonConvenience wrapper to set the "version" property in package.json with the git tag.
In unstamped builds (typically those without --stamp) the version will be set to 0.0.0.
This ensures that actions which use the package.json file can get cache hits.
For more information on stamping, read https://docs.aspect.build/rules/bazel_lib/docs/stamping.
Parameters
*name | name of the resulting |
*stamp_var | a key from the bazel-out/stable-status.txt or bazel-out/volatile-status.txt files |
kwargs | additional attributes passed to the jq rule, see https://docs.aspect.build/rules/bazel_lib/docs/jq |
@aspect_rules_js//npm:extensions.bzl
Adapt npm repository rules to be called from MODULE.bazel
See https://bazel.build/docs/bzlmod#extension-definition
Module Extensions
npmTag Classes
npm_translate_lockRepository macro to generate starlark code from a lock file.
In most repositories, it would be an impossible maintenance burden to manually declare all
of the npm_import rules. This helper generates an external repository
containing a helper starlark module repositories.bzl, which supplies a loadable macro
npm_repositories. That macro creates an npm_import for each package.
The generated repository also contains:
- A
defs.bzlfile containing some rules such asnpm_link_all_packages, which are documented here. BUILDfiles declaring targets for the packages listed asdependenciesordevDependenciesinpackage.json,
so you can declare dependencies on those packages without having to repeat version information.
This macro creates a pnpm external repository, if the user didn't create a repository named
"pnpm" prior to calling npm_translate_lock.
rules_js currently only uses this repository when npm_package_lock or yarn_lock are used.
Set pnpm_version to None to inhibit this repository creation.
For more about how to use npm_translate_lock, read pnpm and rules_js.
Args:
name: The repository rule name
pnpm_lock: The `pnpm-lock.yaml` file.
npm_package_lock: The `package-lock.json` file written by `npm install`.
Only one of `npm_package_lock` or `yarn_lock` may be set.
yarn_lock: The `yarn.lock` file written by `yarn install`.
Only one of `npm_package_lock` or `yarn_lock` may be set.
update_pnpm_lock: When True, the pnpm lock file will be updated automatically when any of its inputs
have changed since the last update.
Defaults to True when one of `npm_package_lock` or `yarn_lock` are set.
Otherwise it defaults to False.
Read more: [using update_pnpm_lock](/docs/pnpm.md#update_pnpm_lock)
node_toolchain_prefix: the prefix of the node toolchain to use when generating the pnpm lockfile.
preupdate: Node.js scripts to run in this repository rule before auto-updating the pnpm lock file.
Scripts are run sequentially in the order they are listed. The working directory is set to the root of the
external repository. Make sure all files required by preupdate scripts are added to the `data` attribute.
A preupdate script could, for example, transform `resolutions` in the root `package.json` file from a format
that yarn understands such as `@foo/**/bar` to the equivalent `@foo/*>bar` that pnpm understands so that
`resolutions` are compatible with pnpm when running `pnpm import` to update the pnpm lock file.
Only needed when `update_pnpm_lock` is True.
Read more: [using update_pnpm_lock](/docs/pnpm.md#update_pnpm_lock)
npmrc: The `.npmrc` file, if any, to use.
When set, the `.npmrc` file specified is parsed and npm auth tokens and basic authentication configuration
specified in the file are passed to the Bazel downloader for authentication with private npm registries.
In a future release, pnpm settings such as public-hoist-patterns will be used.
use_home_npmrc: Use the `$HOME/.npmrc` file (or `$USERPROFILE/.npmrc` when on Windows) if it exists.
Settings from home `.npmrc` are merged with settings loaded from the `.npmrc` file specified
in the `npmrc` attribute, if any. Where there are conflicting settings, the home `.npmrc` values
will take precedence.
WARNING: The repository rule will not be invalidated by changes to the home `.npmrc` file since there
is no way to specify this file as an input to the repository rule. If changes are made to the home
`.npmrc` you can force the repository rule to re-run and pick up the changes by running:
`bazel run @{name}//:sync` where `name` is the name of the `npm_translate_lock` you want to re-run.
Because of the repository rule invalidation issue, using the home `.npmrc` is not recommended.
`.npmrc` settings should generally go in the `npmrc` in your repository so they are shared by all
developers. The home `.npmrc` should be reserved for authentication settings for private npm repositories.
data: Data files required by this repository rule when auto-updating the pnpm lock file.
Only needed when `update_pnpm_lock` is True.
Read more: [using update_pnpm_lock](/docs/pnpm.md#update_pnpm_lock)
patches: A map of package names or package names with their version (e.g., "my-package" or "my-package@v1.2.3")
to a label list of patches to apply to the downloaded npm package. Multiple matches are additive.
These patches are applied after any patches in [pnpm.patchedDependencies](https://pnpm.io/next/package_json#pnpmpatcheddependencies).
Read more: [patching](/docs/pnpm.md#patching)
patch_tool: The patch tool to use. If not specified, the `patch` from `PATH` is used.
patch_args: A map of package names or package names with their version (e.g., "my-package" or "my-package@v1.2.3")
to a label list arguments to pass to the patch tool. The most specific match wins.
Read more: [patching](/docs/pnpm.md#patching)
custom_postinstalls: A map of package names or package names with their version (e.g., "my-package" or "my-package@v1.2.3")
to a custom postinstall script to apply to the downloaded npm package after its lifecycle scripts runs.
If the version is left out of the package name, the script will run on every version of the npm package. If
a custom postinstall scripts exists for a package as well as for a specific version, the script for the versioned package
will be appended with `&&` to the non-versioned package script.
For example,
```
custom_postinstalls = {
"@foo/bar": "echo something > somewhere.txt",
"fum@0.0.1": "echo something_else > somewhere_else.txt",
},
```
Custom postinstalls are additive and joined with ` && ` when there are multiple matches for a package.
More specific matches are appended to previous matches.
package_visibility: A map of package names or package names with their version (e.g., "my-package" or "my-package@v1.2.3")
to a visibility list to use for the package's generated node_modules link targets. Multiple matches are additive.
If there are no matches then the package's generated node_modules link targets default to public visibility
(`["//visibility:public"]`).
public_hoist_packages: A map of package names or package names with their version (e.g., "my-package" or "my-package@v1.2.3")
to a list of Bazel packages in which to hoist the package to the top-level of the node_modules tree when linking.
This is similar to setting https://pnpm.io/npmrc#public-hoist-pattern in an .npmrc file outside of Bazel, however,
wild-cards are not yet supported and npm_translate_lock will fail if there are multiple versions of a package that
are to be hoisted.
```
public_hoist_packages = {
"@foo/bar": [""] # link to the root package
"fum@0.0.1": ["some/sub/package"]
},
```
List of public hoist packages are additive when there are multiple matches for a package. More specific matches
are appended to previous matches.
no_dev: If True, `devDependencies` are not included
no_optional: If True, `optionalDependencies` are not installed.
Currently `npm_translate_lock` behaves differently from pnpm in that is downloads all `optionaDependencies`
while pnpm doesn't download `optionalDependencies` that are not needed for the platform pnpm is run on.
See https://github.com/pnpm/pnpm/pull/3672 for more context.
run_lifecycle_hooks: Sets a default value for `lifecycle_hooks` if `*` not already set.
Set this to `False` to disable lifecycle hooks.
lifecycle_hooks: A dict of package names to list of lifecycle hooks to run for that package.
By default the `preinstall`, `install` and `postinstall` hooks are run if they exist. This attribute allows
the default to be overridden for packages to run `prepare`.
List of hooks are not additive. The most specific match wins.
Read more: [lifecycles](/docs/pnpm.md#lifecycles)
lifecycle_hooks_exclude: A list of package names or package names with their version (e.g., "my-package" or "my-package@v1.2.3")
to not run any lifecycle hooks on.
Equivalent to adding `<value>: []` to `lifecycle_hooks`.
Read more: [lifecycles](/docs/pnpm.md#lifecycles)
lifecycle_hooks_envs: Environment variables set for the lifecycle hooks actions on npm packages.
The environment variables can be defined per package by package name or globally using "*".
Variables are declared as key/value pairs of the form "key=value".
Multiple matches are additive.
Read more: [lifecycles](/docs/pnpm.md#lifecycles)
lifecycle_hooks_execution_requirements: Execution requirements applied to the preinstall, install and postinstall
lifecycle hooks on npm packages.
The execution requirements can be defined per package by package name or globally using "*".
Execution requirements are not additive. The most specific match wins.
Read more: [lifecycles](/docs/pnpm.md#lifecycles)
lifecycle_hooks_no_sandbox: If True, a "no-sandbox" execution requirement is added to all lifecycle hooks
unless overridden by `lifecycle_hooks_execution_requirements`.
Equivalent to adding `"*": ["no-sandbox"]` to `lifecycle_hooks_execution_requirements`.
This defaults to True to limit the overhead of sandbox creation and copying the output
TreeArtifacts out of the sandbox.
Read more: [lifecycles](/docs/pnpm.md#lifecycles)
lifecycle_hooks_use_default_shell_env: The `use_default_shell_env` attribute of the lifecycle hooks
actions on npm packages.
See [use_default_shell_env](https://bazel.build/rules/lib/builtins/actions#run.use_default_shell_env)
This defaults to False reduce the negative effects of `use_default_shell_env`.
Read more: [lifecycles](/docs/pnpm.md#lifecycles)
bins: Binary files to create in `node_modules/.bin` for packages in this lock file.
For a given package, this is typically derived from the "bin" attribute in
the package.json file of that package.
For example:
```
bins = {
"@foo/bar": {
"foo": "./foo.js",
"bar": "./bar.js"
},
}
```
Dicts of bins not additive. The most specific match wins.
In the future, this field may be automatically populated from information in the pnpm lock
file. That feature is currently blocked on https://github.com/pnpm/pnpm/issues/5131.
Note: Bzlmod users must use an alternative syntax due to module extensions not supporting
dict-of-dict attributes:
```
bins = {
"@foo/bar": [
"foo=./foo.js",
"bar=./bar.js"
],
}
```
verify_node_modules_ignored: **Bazel 7.x only (deprecated)** - Verifies node_modules folders are ignored.
This points to a `.bazelignore` file to verify that all nested node_modules directories
pnpm will create are listed.
**Bazel 8+**: Use `ignore_directories(["**/node_modules"])` in REPO.bazel instead.
See https://github.com/bazelbuild/bazel/issues/8106
verify_patches: Label to a patch list file.
Use this in together with the `list_patches` macro to guarantee that all patches in a patch folder
are included in the `patches` attribute.
For example:
```
verify_patches = "//patches:patches.list",
```
In your patches folder add a BUILD.bazel file containing.
```
load("@aspect_rules_js//npm:repositories.bzl", "list_patches")
list_patches(
name = "patches",
out = "patches.list",
)
```
Once you have created this file, you need to create an empty `patches.list` file before generating the first list. You can do this by running
```
touch patches/patches.list
```
Finally, write the patches file at least once to make sure all patches are listed. This can be done by running `bazel run //patches:patches_update`.
See the `list_patches` documentation for further info.
NOTE: if you would like to customize the patches directory location, you can set a flag in the `.npmrc`. Here is an example of what this might look like
```
# Set the directory for pnpm when patching
# https://github.com/pnpm/pnpm/issues/6508#issuecomment-1537242124
patches-dir=bazel/js/patches
```
If you do this, you will have to update the `verify_patches` path to be this path instead of `//patches` like above.
quiet: Set to False to print info logs and output stdout & stderr of pnpm lock update actions to the console.
external_repository_action_cache: The location of the external repository action cache to write to when `update_pnpm_lock` = True.
use_pnpm: label of the pnpm entry point to use.
npm_package_target_name: The name of linked `js_library`, `npm_package` or `JsInfo` producing targets.
When targets are linked as pnpm workspace packages, the name of the target must align with this value.
The `{dirname}` placeholder is replaced with the directory name of the target.
**kwargs: Internal use only
| Attribute | Type | Description |
|---|---|---|
bins | dictionary: String → List of strings | Default: {} |
custom_postinstalls | dictionary: String → String | Default: {} |
data | list of labels | Default: [] |
external_repository_action_cache | string | Default: ".aspect/rules/external_repository_action_cache" |
generate_bzl_library_targets | boolean | Default: False |
lifecycle_hooks_envs | dictionary: String → List of strings | Default: {} |
lifecycle_hooks | dictionary: String → List of strings | Default: {} |
lifecycle_hooks_exclude | list of strings | Default: [] |
lifecycle_hooks_execution_requirements | dictionary: String → List of strings | Default: {} |
lifecycle_hooks_use_default_shell_env | dictionary: String → String | Default: {} |
lifecycle_hooks_no_sandbox | boolean | Default: True |
name | name | Default: "" |
no_dev | boolean | Default: False |
no_optional | boolean | Default: False |
node_toolchain_prefix | string | Default: "nodejs" |
npm_package_lock | label | Default: None |
npm_package_target_name | string | Default: "pkg" |
npmrc | label | Default: None |
package_visibility | dictionary: String → List of strings | Default: {} |
patch_tool | label | Default: None |
patch_args | dictionary: String → List of strings | Default: {"*": ["-p0"]} |
patches | dictionary: String → List of strings | Default: {} |
use_pnpm | label | Default: "@pnpm//:package/bin/pnpm.cjs" |
pnpm_lock | label | Default: None |
preupdate | list of labels | Default: [] |
public_hoist_packages | dictionary: String → List of strings | Default: {} |
quiet | boolean | Default: True |
run_lifecycle_hooks | boolean | Default: True |
update_pnpm_lock | boolean | Default: False |
use_home_npmrc | boolean | Default: False |
verify_node_modules_ignored | label | Default: None |
verify_patches | label | Default: None |
yarn_lock | label | Default: None |
npm_importImport a single npm package into Bazel.
Normally you'd want to use npm_translate_lock to import all your packages at once.
It generates npm_import rules.
You can create these manually if you want to have exact control.
Bazel will only fetch the given package from an external registry if the package is
required for the user-requested targets to be build/tested.
For example, in MODULE.bazel:
npm.npm_import( name = "npm__at_types_node__15.12.2", package = "@types/node", version = "15.12.2", integrity = "sha512-zjQ69G564OCIWIOHSXyQEEDpdpGl+G348RAKY0XXy9Z5kU9Vzv1GMNnkar/ZJ8dzXB3COzD9Mo9NtRZ4xfgUww==", ) use_repo(npm, "npm__at_types_node__15.12.2") use_repo(npm, "npm__at_types_node__15.12.2__links")
This is similar to Bazel rules in other ecosystems named "_import" like
apple_bundle_import,scala_import,java_import, andpy_import.
go_repositoryis also a model for this rule.
The name of this repository should contain the version number, so that multiple versions of the same
package don't collide.
(Note that the npm ecosystem always supports multiple versions of a library depending on where
it is required, unlike other languages like Go or Python.)
To consume the downloaded package in rules, it must be "linked" into the link package in the
package's BUILD.bazel file:
load("@npm__at_types_node__15.12.2__links//:defs.bzl", npm_link_types_node = "npm_link_imported_package")
npm_link_types_node()
This links @types/node into the node_modules of this package with the target name :node_modules/@types/node.
A :node_modules/@types/node/dir filegroup target is also created that provides the the directory artifact of the npm package.
This target can be used to create entry points for binary target or to access files within the npm package.
NB: You can choose any target name for the link target but we recommend using the node_modules/@scope/name and
node_modules/name convention for readability.
When using npm_translate_lock, you can link all the npm dependencies in the lock file for a package:
load("@npm//:defs.bzl", "npm_link_all_packages")
npm_link_all_packages()
This creates :node_modules/name and :node_modules/@scope/name targets for all direct npm dependencies in the package.
It also creates :node_modules/name/dir and :node_modules/@scope/name/dir filegroup targets that provide the the directory artifacts of their npm packages.
These target can be used to create entry points for binary target or to access files within the npm package.
If you have a mix of npm_link_all_packages and npm_link_imported_package functions to call you can pass the
npm_link_imported_package link functions to the imported_links attribute of npm_link_all_packages to link
them all in one call. For example,
load("@npm//:defs.bzl", "npm_link_all_packages")
load("@npm__at_types_node__15.12.2__links//:defs.bzl", npm_link_types_node = "npm_link_imported_package")
npm_link_all_packages(
imported_links = [
npm_link_types_node,
]
)
This has the added benefit of adding the imported_links to the convienence :node_modules target which
includes all direct dependencies in that package.
NB: You can pass an name to npm_link_all_packages and this will change the targets generated to "{name}/@scope/name" and
"{name}/name". We recommend using "node_modules" as the convention for readability.
To change the proxy URL we use to fetch, configure the Bazel downloader:
-
Make a file containing a rewrite rule like
rewrite (registry.npmjs.org)/(.*) artifactory.build.internal.net/artifactory/$1/$2 -
To understand the rewrites, see UrlRewriterConfig in Bazel sources.
-
Point bazel to the config with a line in .bazelrc like
common --experimental_downloader_config=.bazel_downloader_config
Read more about the downloader config: https://blog.aspect.build/configuring-bazels-downloader
Args:
name: Name for this repository rule
package: Name of the npm package, such as `acorn` or `@types/node`
version: Version of the npm package, such as `8.4.0`
deps: A dict other npm packages this one depends on where the key is the package name and value is the version
root_package: The root package where the node_modules package store is linked to.
Typically this is the package that the pnpm-lock.yaml file is located when using `npm_translate_lock`.
lifecycle_hooks: List of lifecycle hook `package.json` scripts to run for this package if they exist.
lifecycle_hooks_env: Environment variables set for the lifecycle hooks action for this npm
package if there is one.
Environment variables are defined by providing an array of "key=value" entries.
For example:
```
lifecycle_hooks_env: ["PREBULT_BINARY=https://downloadurl"],
```
lifecycle_hooks_execution_requirements: Execution requirements when running the lifecycle hooks.
For example:
```
lifecycle_hooks_execution_requirements: ["no-sandbox', "requires-network"]
```
This defaults to ["no-sandbox"] to limit the overhead of sandbox creation and copying the output
TreeArtifact out of the sandbox.
lifecycle_hooks_use_default_shell_env: If True, the `use_default_shell_env` attribute of lifecycle hook
actions is set to True.
See [use_default_shell_env](https://bazel.build/rules/lib/builtins/actions#run.use_default_shell_env)
This defaults to False reduce the negative effects of `use_default_shell_env`.
integrity: Expected checksum of the file downloaded, in Subresource Integrity format.
This must match the checksum of the file downloaded.
This is the same as appears in the pnpm-lock.yaml, yarn.lock or package-lock.json file.
It is a security risk to omit the checksum as remote files can change.
At best omitting this field will make your build non-hermetic.
It is optional to make development easier but should be set before shipping.
url: Optional url for this package. If unset, a default npm registry url is generated from
the package name and version.
May start with `git+ssh://` or `git+https://` to indicate a git repository. For example,
```
git+ssh://git@github.com/org/repo.git
```
If url is configured as a git repository, the commit attribute must be set to the
desired commit.
commit: Specific commit to be checked out if url is a git repository.
replace_package: Use the specified npm_package target when linking instead of the fetched sources for this npm package.
The injected npm_package target may optionally contribute transitive npm package dependencies on top
of the transitive dependencies specified in the pnpm lock file for the same package, however, these
transitive dependencies must not collide with pnpm lock specified transitive dependencies.
Any patches specified for this package will be not applied to the injected npm_package target. They
will be applied, however, to the fetches sources so they can still be useful for patching the fetched
`package.json` file, which is used to determine the generated bin entries for the package.
NB: lifecycle hooks and custom_postinstall scripts, if implicitly or explicitly enabled, will be run on
the injected npm_package. These may be disabled explicitly using the `lifecycle_hooks` attribute.
package_visibility: Visibility of generated node_module link targets.
patch_tool: The patch tool to use. If not specified, the `patch` from `PATH` is used.
patch_args: Arguments to pass to the patch tool.
`-p1` will usually be needed for patches generated by git.
patches: Patch files to apply onto the downloaded npm package.
custom_postinstall: Custom string postinstall script to run on the installed npm package.
Runs after any existing lifecycle hooks if any are enabled.
npm_auth: Auth token to authenticate with npm. When using Bearer authentication.
npm_auth_basic: Auth token to authenticate with npm. When using Basic authentication.
This is typically the base64 encoded string "username:password".
npm_auth_username: Auth username to authenticate with npm. When using Basic authentication.
npm_auth_password: Auth password to authenticate with npm. When using Basic authentication.
extra_build_content: Additional content to append on the generated BUILD file at the root of
the created repository, either as a string or a list of lines similar to
<https://github.com/bazelbuild/bazel-skylib/blob/main/docs/write_file_doc.md>.
bins: Dictionary of `node_modules/.bin` binary files to create mapped to their node entry points.
This is typically derived from the "bin" attribute in the package.json
file of the npm package being linked.
For example:
```
bins = {
"foo": "./foo.js",
"bar": "./bar.js",
}
```
In the future, this field may be automatically populated by npm_translate_lock
from information in the pnpm lock file. That feature is currently blocked on
https://github.com/pnpm/pnpm/issues/5131.
exclude_package_contents: List of glob patterns to exclude from the linked package.
This is useful for excluding files that are not needed in the linked package.
For example:
```
exclude_package_contents = ["**/tests/**"]
```
**kwargs: Internal use only
| Attribute | Type | Description |
|---|---|---|
*package | string | |
root_package | string | Default: "" |
*version | string | |
exclude_package_contents | list of strings | Default: [] |
exclude_package_contents_presets | list of strings | Default: ["basic"] |
commit | string | Default: "" |
custom_postinstall | string | Default: "" |
extra_build_content | string | Default: "" |
extract_full_archive | boolean | Default: False |
integrity | string | Default: "" |
lifecycle_hooks | list of strings | Default: [] |
npm_auth | string | Default: "" |
npm_auth_basic | string | Default: "" |
npm_auth_password | string | Default: "" |
npm_auth_username | string | Default: "" |
patch_tool | label | Default: None |
patch_args | list of strings | Default: ["-p0"] |
patches | list of labels | Default: [] |
url | string | Default: "" |
bins | dictionary: String → String | Default: {} |
deps | dictionary: String → String | Mapping of dependency link names to package store keys Default: {} |
lifecycle_build_target | boolean | Default: False |
lifecycle_hooks_env | list of strings | Default: [] |
lifecycle_hooks_execution_requirements | list of strings | Default: ["no-sandbox"] |
lifecycle_hooks_use_default_shell_env | boolean | Default: False |
package_visibility | list of strings | Default: ["//visibility:public"] |
replace_package | string | Default: "" |
name | name | Default: "" |
lifecycle_hooks_no_sandbox | boolean | Default: False |
run_lifecycle_hooks | boolean | Default: False |
npm_exclude_package_contentsConfiguration for excluding package contents from npm packages.
This tag can be used multiple times to specify different exclusion patterns for different package specifiers.
More specific package matches override less specific ones (the wildcard "*" is only used if no specific
package match is found).
By default, presets is set to ["basic"] which excludes common files such as *.md and development-related
files. Multiple presets can be combined.
Example:
npm.npm_exclude_package_contents(
package = "*",
patterns = ["**/docs/**"],
)
npm.npm_exclude_package_contents(
package = "my-package@1.2.3",
# Overrides the "*" config for this specific package
presets = ["yarn_autoclean"],
)
| Attribute | Type | Description |
|---|---|---|
*package | string | Package name to apply exclusions to. Supports wildcards like '*' for all packages. |
patterns | list of strings | List of glob patterns to exclude from the specified package. Default: [] |
presets | list of strings | Which preset exclusion patterns to include. Multiple presets can be combined. Valid values:
Default: ["basic"] |
npm_replace_packageReplace a package with a custom target.
This allows replacing packages declared in package.json with custom implementations.
Multiple npm_replace_package tags can be used to replace different packages.
Targets must produce JsInfo or NpmPackageInfo providers such as js_library or npm_package targets.
The injected package targets may optionally contribute transitive npm package dependencies on top
of the transitive dependencies specified in the pnpm lock file for their respective packages, however, these
transitive dependencies must not collide with pnpm lock specified transitive dependencies.
Any patches specified for the packages will be not applied to the injected package targets. They
will be applied, however, to the fetches sources for their respecitve packages so they can still be useful
for patching the fetched package.json files, which are used to determine the generated bin entries for packages.
NB: lifecycle hooks and custom_postinstall scripts, if implicitly or explicitly enabled, will be run on
the injected package targets. These may be disabled explicitly using the lifecycle_hooks attribute.
Example:
npm.npm_replace_package( package = "chalk@5.3.0", replacement = "@chalk_501//:pkg", )
| Attribute | Type | Description |
|---|---|---|
*package | string | The package name and version to replace (e.g., 'chalk@5.3.0') |
*replacement | label | The target to use as replacement for this package |
pnpmTag Classes
pnpm| Attribute | Type | Description |
|---|---|---|
name | name | Name of the generated repository, allowing more than one pnpm version to be registered. Default: "pnpm" |
include_npm | boolean | If true, include the npm package along with the pnpm binary. Default: False |
pnpm_version | string | pnpm version to use. The string Default: "10.28.1" |
pnpm_version_from | label | Label to a package.json file to read the pnpm version from. It should be in the packageManager attribute. Default: None |
pnpm_version_integrity | string | Default: "" |