Search code examples
typescriptbazel

bazel: '@bazel/typescript' is not a package


My attempt loading ts_project fails with the error message below:

ERROR: error loading package '': Label '@npm//@bazel/typescript:index.bzl' is invalid because '@bazel/typescript' is not a package; perhaps you meant to put the colon here: '@npm//:@bazel/typescript/index.bzl'?

WORKSPACE:

workspace(
    name = "nodejs",
    managed_directories = {"@npm": ["node_modules"]},
)

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
    name = "build_bazel_rules_nodejs",
    sha256 = "cfc289523cf1594598215901154a6c2515e8bf3671fd708264a6f6aefe02bf39",
    urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/4.4.6/rules_nodejs-4.4.6.tar.gz"],
)

load("@build_bazel_rules_nodejs//:index.bzl", "npm_install")
npm_install(
    name = "npm",
    package_json = "//:package.json",
    package_lock_json = "//:package-lock.json",
)

BUILD:

load("@npm//@bazel/typescript:index.bzl", "ts_project")
load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_test")

ts_project(
  name = "lib",
  srcs = glob(["src/**/*.ts"]),
  tsconfig = "tsconfig.json",
  deps = [
    "@npm//@types/lodash"
  ],
  declaration = True,
  source_map = True,
)

nodejs_test(
  name = "index_test",
  entry_point = ":src/index.ts",
  data = [
    "@npm//lodash",
    ":lib"
  ],
)

What's wrong?


Solution

  • Let's say you have a minimal package.json that you're not showing us here, say

    {
        "name": "test",
        "version": "1.0.0"
    }
    

    Then if you check what's in @npm, you will see that there are no packages defined inside of it.

    ❯ bazel query @npm//...
    @npm//:node_modules
    Loading: 1 packages loaded
    

    You'll need to add @bazel/typescript to your package.json to have npm_install make it available to you. So run

    ❯ npm install @bazel/typescript
    
    up to date, audited 25 packages in 644ms
    
    found 0 vulnerabilities
    

    package.json now has

    {
        "name": "test",
        "version": "1.0.0",
        "dependencies": {
            "@bazel/typescript": "^4.4.6"
        }
    }
    

    and our Bazel query now shows a bunch of available packages:

    ❯ bazel query @npm//...
    @npm//tsutils:tsutils__umd
    @npm//tsutils:tsutils__typings
    @npm//tsutils:tsutils__all_files
    [...]
    @npm//@bazel/typescript:typescript__nested_node_modules
    @npm//@bazel/typescript:typescript__files
    Loading: 0 packages loaded
    

    including the one that the load statement was previously not finding. At this point you can try to build your package again, making sure to add all the dependencies you need (like lodash).