使用'ts_library'中的非'.ts'/'.tsx'文件作为依赖项



我正在尝试从打字稿导入一个 json 文件(是的,我在我的 tsconfig 中使用了resolveJsonModule标志(。问题是,我不知道如何将此 json 文件提供给ts_library(这也适用于任何其他非.ts&.tsx文件,例如.env(。ts_library总是告诉我他找不到我的 JSON 文件。

例如,如果我在BUILD.bazel中有此ts_library

ts_library(
name = "src",
srcs = glob(["*.ts"]),
deps = [
"@npm//:node_modules",
]
)

有了这个index.ts

import test from './test.json';
console.log(test);

而这个test.json

{
"foo": "bar"
}

它会扔给我这个:

index.ts:1:18 - error TS2307: Cannot find module './test.json'.

我想我需要以某种方式在我的规则deps中添加 json 文件。但我不知道该怎么做,因为 deps 不接受像//:test.json这样的直接文件。

您可以通过data属性 (https://www.npmjs.com/package/@bazel/typescript#data( 将文件添加到ts_library规则中。您可以在此处添加对 JSON 文件的引用。

但是,ts_library覆盖输出模块格式,resolveJsonModule只能与commonjs,amd,es2015或esNext一起使用(ts_library将其覆盖为UMD(。

Option '--resolveJsonModule' can only be specified when module code generation is 'commonjs', 'amd', 'es2015' or 'esNext'.

如果您直接通过 Bazel 而不是通过 ts_library 使用打字稿编译器,则可以执行此操作:

load("@npm//typescript:index.bzl", "tsc")
srcs = glob(["*.ts"])
deps = ["@npm//@types/node"]
data = ["test.json"]
tsc(
name = "src",
data = srcs + deps + data,
outs = [s.replace(".ts", ext) for ext in [".js", ".d.ts"] for s in srcs],
args = [
"--outDir",
"$(RULEDIR)",
"--lib",
"es2017,dom",
"--downlevelIteration",
"--declaration",
"--resolveJsonModule",
] + [
"$(location %s)" % s
for s in srcs
],
)

您可以使用nodejs_binary测试它是否有效:

load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_binary")
nodejs_binary(
name = "src_bin",
data = [
":src",
] + data,
entry_point = "//src:index.ts",
)

有关此内容的更多信息,请使用tsc而不是ts_library: https://github.com/bazelbuild/rules_nodejs/blob/master/packages/typescript/docs/install.md

最新更新