You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bazel rules_nodejs执行yarn_install/npm_install后如何访问node_modules文件夹

问题原因

rules_nodejs的yarn_install规则默认不会生成@npm//node_modules这个子包目标,它会将每个npm依赖拆分为独立的Bazel目标,你尝试访问的路径实际不存在,因此触发了包不存在的报错。而单独引用@npm//express这类单个依赖可以正常运行,是因为yarn_install会为每个安装的npm包自动生成对应名称的独立目标。

解决方案

如果你确实需要将完整的node_modules目录加入镜像,直接引用@npm工作区根目录下的node_modules聚合目标即可,目标写法为@npm//:node_modules。

修正后的BUILD.bazel配置如下:

load("@io_bazel_rules_docker//nodejs:image.bzl", "nodejs_image")

nodejs_image(
    name = "webapi_image",
    data = glob(
        [
            "**/*",
        ],
    ) + ["@npm//:node_modules"],
    entry_point = "//:app.js",
)

优化建议

引入完整node_modules会额外增加镜像体积、降低构建速度,若你的项目仅依赖部分npm包,更推荐显式逐个声明用到的依赖,示例如下:

data = glob(["**/*"]) + [
    "@npm//express",
    "@npm//cors",
    # 其他用到的依赖
]

内容的提问来源于stack exchange,提问作者Cameron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 12:18:03