Skip to content

Commit

Permalink
feat(typescript): generate tsconfig.json for ts_project
Browse files Browse the repository at this point in the history
This is an experimental, opt-in feature where ts_project will generate a tsconfig.json file in place of
the user specifying one in the source directory.

I expect a long tail of compatibility bugs since any path appearing in this generated file needs to point from
bazel-out back to the source directory.

Fixes #2058
  • Loading branch information
Alex Eagle committed Aug 23, 2020
1 parent 660b456 commit d0d6bf3
Show file tree
Hide file tree
Showing 22 changed files with 275 additions and 42 deletions.
37 changes: 11 additions & 26 deletions packages/typescript/checked_in_ts_project.bzl
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"checked_in_ts_project rule"

load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test")
load("@build_bazel_rules_nodejs//third_party/github.com/bazelbuild/bazel-skylib:rules/write_file.bzl", "write_file")
load("//packages/typescript:index.bzl", "ts_project")

def checked_in_ts_project(name, src, checked_in_js = None, **kwargs):
Expand All @@ -15,34 +14,20 @@ def checked_in_ts_project(name, src, checked_in_js = None, **kwargs):
if not checked_in_js:
checked_in_js = src[:-3] + ".js"

tsconfig = "tsconfig_%s.json" % name

# workspace is up three dirs (bazel-out/arch/bin) plus number of segments in the package
workspace_root = "/".join([".."] * (3 + len(native.package_name().split("/"))))

# Generate a tsconfig, this is partly an example of how it can be done, per jbedard and toxicable request
write_file(
name = "_gen_tsconfig_%s" % name,
content = [struct(
compilerOptions = struct(
lib = ["es2017", "dom"],
strict = True,
target = "es2015",
module = "commonjs",
removeComments = True,
declaration = True,
skipLibCheck = True,
),
files = ["/".join([workspace_root, native.package_name(), src])],
).to_json()],
out = tsconfig,
)

ts_project(
name = name,
srcs = [src],
declaration = True,
tsconfig = tsconfig,
tsconfig = {
"compilerOptions": {
"declaration": True,
"lib": ["es2017", "dom"],
"module": "commonjs",
"removeComments": True,
"skipLibCheck": True,
"strict": True,
"target": "es2015",
},
},
**kwargs
)

Expand Down
73 changes: 73 additions & 0 deletions packages/typescript/internal/ts_config.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,76 @@ feature from TypeScript, then the Bazel implementation needs to know about that
extended configuration file as well, to pass them both to the TypeScript compiler.
""",
)

def _join(*elements):
return "/".join([f for f in elements if f])

def _path_to(f, workspace_root):
if f.is_source:
return _join(workspace_root, f.path)
return f.path

def _write_tsconfig_rule(ctx):
content = "\n".join(ctx.attr.content)
if ctx.attr.extends:
content = content.replace(
"__extends__",
_path_to(ctx.file.extends, ctx.attr.workspace_root),
)
if ctx.attr.files:
content = content.replace(
"\"__files__\"",
str([_path_to(f, ctx.attr.workspace_root) for f in ctx.files.files]),
)
ctx.actions.write(
output = ctx.outputs.out,
content = content,
)
return [DefaultInfo(files = depset([ctx.outputs.out]))]

write_tsconfig_rule = rule(
implementation = _write_tsconfig_rule,
attrs = {
"content": attr.string_list(),
"extends": attr.label(allow_single_file = True),
"files": attr.label_list(allow_files = True),
"out": attr.output(),
"workspace_root": attr.string(),
},
)

# Syntax sugar around skylib's write_file
def write_tsconfig(name, config, files, extends, out):
"""Wrapper around bazel_skylib's write_file which understands tsconfig paths
Args:
name: name of the resulting write_file rule
config: tsconfig dictionary
files: list of input .ts files to put in the files[] array
extends: a tsconfig.json file to extend from
out: the file to write
"""

# Allow extends to be a list of labels, as this is what ts_project accepts
if type(extends) == type([]):
if len(extends):
extends = extends[0]
else:
extends = None
if extends:
extends = Label(extends)
config["extends"] = "__extends__" #_join(workspace_root, extends.package, extends.name)

amended_config = struct(
files = "__files__", #[_join(workspace_root, native.package_name(), f) for f in files],
**config
)
write_tsconfig_rule(
name = name,
files = files,
extends = extends,
content = [amended_config.to_json()],
# workspace is up three dirs (bazel-out/arch/bin) plus number of segments in the package
workspace_root = "/".join([".."] * (3 + len(native.package_name().split("/")))),
out = out,
)
61 changes: 45 additions & 16 deletions packages/typescript/internal/ts_project.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

load("@build_bazel_rules_nodejs//:providers.bzl", "DeclarationInfo", "NpmPackageInfo", "declaration_info", "js_module_info", "run_node")
load("@build_bazel_rules_nodejs//internal/linker:link_node_modules.bzl", "module_mappings_aspect")
load(":ts_config.bzl", "write_tsconfig")

_DEFAULT_TSC = (
# BEGIN-INTERNAL
Expand Down Expand Up @@ -353,6 +354,10 @@ def ts_project_macro(
By default, we add `.json` to the `name` attribute.
EXPERIMENTAL: instead of a label, pass a dictionary of tsconfig keys.
in this case, a tsconfig.json file will be generated for this compilation.
Each file in srcs will be converted to a relative path in the `files` section.
extends: List of labels of tsconfig file(s) referenced in `extends` section of tsconfig.
Must include any tsconfig files "chained" by extends clauses.
Expand Down Expand Up @@ -400,26 +405,50 @@ def ts_project_macro(

if srcs == None:
srcs = native.glob(["**/*.ts", "**/*.tsx"])

if tsconfig == None:
tsconfig = name + ".json"

extra_deps = []

if validate:
validate_options(
name = "_validate_%s_options" % name,
target = "//%s:%s" % (native.package_name(), name),
declaration = declaration,
source_map = source_map,
declaration_map = declaration_map,
composite = composite,
incremental = incremental,
emit_declaration_only = emit_declaration_only,
tsconfig = tsconfig,
if type(tsconfig) == type(dict()):
# Copy attributes <-> tsconfig properties
# TODO: fail if compilerOptions includes a conflict with an attribute?
compiler_options = tsconfig.setdefault("compilerOptions", {})
source_map = compiler_options.setdefault("sourceMap", source_map)
declaration = compiler_options.setdefault("declaration", declaration)
declaration_dir = compiler_options.setdefault("declarationDir", declaration_dir)
declaration_map = compiler_options.setdefault("declarationMap", declaration_map)
emit_declaration_only = compiler_options.setdefault("emitDeclarationOnly", emit_declaration_only)
out_dir = compiler_options.setdefault("outDir", out_dir)
declaration_dir = compiler_options.setdefault("declarationDir", declaration_dir)
root_dir = compiler_options.setdefault("rootDir", root_dir)
write_tsconfig(
name = "_gen_tsconfig_%s" % name,
config = tsconfig,
files = srcs,
extends = extends,
out = "tsconfig_%s.json" % name,
)
extra_deps.append("_validate_%s_options" % name)

# From here, tsconfig becomes a file, the same as if the
# user supplied a tsconfig.json InputArtifact
tsconfig = "tsconfig_%s.json" % name

else:
if tsconfig == None:
tsconfig = name + ".json"

if validate:
validate_options(
name = "_validate_%s_options" % name,
target = "//%s:%s" % (native.package_name(), name),
declaration = declaration,
source_map = source_map,
declaration_map = declaration_map,
composite = composite,
incremental = incremental,
emit_declaration_only = emit_declaration_only,
tsconfig = tsconfig,
extends = extends,
)
extra_deps.append("_validate_%s_options" % name)

typings_out_dir = declaration_dir if declaration_dir else out_dir

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"Test that attributes set on ts_project are honored"

load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test")
load("//packages/typescript:index.bzl", "ts_project")

ts_project(
tsconfig = {
"compilerOptions": {
"declaration": True,
"declarationDir": "types",
"declarationMap": True,
"listEmittedFiles": True,
"module": "esnext",
"outDir": "out",
"rootDir": "src",
"sourceMap": True,
},
},
)

generated_file_test(
name = "test",
src = "expected.js_",
generated = ":out/a.js",
)

generated_file_test(
name = "test_map",
src = "expected.js.map_",
generated = ":out/a.js.map",
)

generated_file_test(
name = "test_dts",
src = "expected.d.ts_",
generated = ":types/a.d.ts",
)

generated_file_test(
name = "test_dtsmap",
src = "expected.d.ts.map_",
generated = ":types/a.d.ts.map",
)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"version":3,"file":"a.d.ts","sourceRoot":"","sources":["../../../../../../../../../../packages/typescript/test/ts_project/generated_tsconfig/config/src/a.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,CAAC,EAAE,MAAsB,CAAC"}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export declare const a: string;
//# sourceMappingURL=a.d.ts.map
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"version":3,"file":"a.js","sourceRoot":"","sources":["../../../../../../../../../../packages/typescript/test/ts_project/generated_tsconfig/config/src/a.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,IAAM,CAAC,GAAW,aAAa,CAAC"}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export var a = 'hello world';
//# sourceMappingURL=a.js.map
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const a: string = 'hello world';
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"Test that attributes set on ts_project are honored"

load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test")
load("//packages/typescript:index.bzl", "ts_project")

ts_project(
declaration = True,
declaration_dir = "types",
declaration_map = True,
out_dir = "out",
root_dir = "src",
source_map = True,
tsconfig = {
"compilerOptions": {
"module": "esnext",
},
},
)

generated_file_test(
name = "test",
src = "expected.js_",
generated = ":out/a.js",
)

generated_file_test(
name = "test_map",
src = "expected.js.map_",
generated = ":out/a.js.map",
)

generated_file_test(
name = "test_dts",
src = "expected.d.ts_",
generated = ":types/a.d.ts",
)

generated_file_test(
name = "test_dtsmap",
src = "expected.d.ts.map_",
generated = ":types/a.d.ts.map",
)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"version":3,"file":"a.d.ts","sourceRoot":"","sources":["../../../../../../../../../../packages/typescript/test/ts_project/generated_tsconfig/config_attrs/src/a.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,CAAC,EAAE,MAAsB,CAAC"}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export declare const a: string;
//# sourceMappingURL=a.d.ts.map
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"version":3,"file":"a.js","sourceRoot":"","sources":["../../../../../../../../../../packages/typescript/test/ts_project/generated_tsconfig/config_attrs/src/a.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,IAAM,CAAC,GAAW,aAAa,CAAC"}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export var a = 'hello world';
//# sourceMappingURL=a.js.map
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const a: string = 'hello world';
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test")
load("//packages/typescript:index.bzl", "ts_project")

ts_project(
name = "compile",
declaration = True,
emit_declaration_only = True,
tsconfig = {},
)

generated_file_test(
name = "test",
# test the default output of the ts_project
src = "a.d.ts",
generated = "compile",
)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const a: string = 'hello world';
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export declare const a: string;
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test")
load("//packages/typescript:index.bzl", "ts_project")

ts_project(
tsconfig = {},
)

generated_file_test(
name = "test",
src = "expected.js_",
generated = ":a.js",
)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const a: string = 'hello world';
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test")
load("//packages/typescript:index.bzl", "ts_project")

ts_project(
declaration = True,
extends = ["//packages/typescript/test/ts_project:tsconfig-base.json"],
tsconfig = {},
)

generated_file_test(
name = "test",
# test the default output of the ts_project
src = "expected.js_",
generated = "a.js",
)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const a: string = 'hello world';

0 comments on commit d0d6bf3

Please sign in to comment.