Bazel rules_nodejs can't resolve modules using custom package.json location.
Can someone help explain how to fix it?
Ideally I'd like to use a single tsconfig.json
in third_party/npm
instead.
bazel build //demo/node:bin
Gives error:
demo/node/src/lib.ts(1,19): error TS2307: Cannot find module 'chalk' or its corresponding type declarations.
Gist: https://gist.github.com/sbussard/9110d1bdcc784ca0a9303d4393e82f49
Folder structure
(repo root)
↳ WORKSPACE
↳ third_party
↳ npm
↳ package.json
↳ yarn.lock
↳ demo
↳ node
↳ BUILD
↳ tsconfig.json
↳ src
↳ lib.ts
WORKSPACE
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "build_bazel_rules_nodejs",
sha256 = "2b2004784358655f334925e7eadc7ba80f701144363df949b3293e1ae7a2fb7b",
urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/5.4.0/rules_nodejs-5.4.0.tar.gz"],
)
load("@build_bazel_rules_nodejs//:repositories.bzl", "build_bazel_rules_nodejs_dependencies")
build_bazel_rules_nodejs_dependencies()
load("@build_bazel_rules_nodejs//:index.bzl", "node_repositories", "yarn_install")
node_repositories()
yarn_install(
name = "npm",
package_json = "//third_party/npm:package.json",
yarn_lock = "//third_party/npm:yarn.lock",
)
BUILD
load("@npm//@bazel/typescript:index.bzl", "ts_project")
load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_binary")
ts_project(
name = "lib",
srcs = glob(["src/*.ts"]),
deps = [
"@npm//@types/chalk",
"@npm//@types/node",
"@npm//chalk",
],
)
nodejs_binary(
name = "bin",
data = [":lib"],
entry_point = "src/lib.js",
)
lib.ts
import chalk from 'chalk';
const { blue, red, green, yellow } = chalk;
const colors = [blue, red, yellow, blue, green, red];
console.log(
'Google'
.split('')
.map((c, i) => colors[i % colors.length](c))
.join('')
);
package.json (inside dependencies)
"@types/chalk": "^2.2.0",
"chalk": "^5.0.1",
tsconfig.json
{
"include": ["src", "types"],
"compilerOptions": {
"module": "es2020",
"target": "esnext",
"moduleResolution": "node",
"baseUrl": "./",
"rootDir": "./",
"paths": {
"src/*": ["src/*"]
},
"strict": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"allowSyntheticDefaultImports": true,
"importsNotUsedAsValues": "error"
}
}