Bazel map directory located outside of `src` to `build`

1.2k Views Asked by At

I have no idea on Bazel or how it works but I have to resolve this issue that finally boiled down to bazel not copying a certain directory into build.

I refactored a code so a certain key ( jwk ) is first tried to read from a directory private-keys. When running it is always file not found. I think bazel is not copying the private-keys directory ( Which is at the same level of src ) into build.

Project/
|-- private-keys\
|-- src/
|   |-- //other directories
|   |-- index.ts
|
|-- package.json
|-- BUILD.bazel

There is a mapping object to copy directories inside src I tried using ../private-keys there but didn't work.

Following is how BUILD.bazel looks like

SOURCES = glob(
    ["src/**/*.ts"],
    exclude = [
        "src/**/*.spec.ts",
        "src/__mocks__/**/*.ts",
    ],
)

mappings_dict = {
    "api": "build/api",
    ....
}

ts_project(
    name = "compile_ts",
    srcs = SOURCES,
    incremental = True,
    out_dir = "build",
    root_dir = "src",
    tsc = "@npm//typescript/bin:tsc",
    tsconfig = ":ts_config_build",
    deps = DEPENDENCIES + TYPE_DEPENDENCIES,
)

ts_project(
    name = "compile_ts",
    srcs = SOURCES,
    incremental = True,
    out_dir = "build",
    root_dir = "src",
    tsc = "@npm//typescript/bin:tsc",
    tsconfig = ":ts_config_build",
    deps = DEPENDENCIES + TYPE_DEPENDENCIES,
)

_mappings = module_mappings(
    name = "mappings",
    mappings = mappings_dict,
)

# Application binary and docker imaage
nodejs_image(
    name = "my-service",
    data = [
        ":compile_ts",
        "@npm//source-map-support",
    ] + _mappings,
    entry_point = "build/index.js",
    templated_args = [
        "--node_options=--require=source-map-support/register",
        "--bazel_patch_module_resolver",
    ],
)
1

There are 1 best solutions below

1
On

The command that builds your target is always run in a separate directory. To tell Bazel it needs to copy over some additional files you need wrap the files in a filegroup target (c.f. bazel docs).

Then add the such filegroup target to the deps attribute of your target.(c.f. the example here).

In your case it'd be something like

filegroup(
  name = "private_keys",
  srcs = glob(["private_keys/**"]),
)

ts_project(
    name = "compile_ts",
    srcs = SOURCES,
    data = [ ":private_keys" ], # <-- !!!
    incremental = True,
    out_dir = "build",
    root_dir = "src",
    tsc = "@npm//typescript/bin:tsc",
    tsconfig = ":ts_config_build",
    deps = DEPENDENCIES + TYPE_DEPENDENCIES,
)

You might also be able to plug the glob(...) directly into the data attribute but, making it a file group makes it reusable... and makes you look like a pro. :)