angular-cn/dev-infra/bazel/expand_template.bzl
Paul Gschwendtner 1601ee6f6a refactor(dev-infra): ng_rollup_bundle rule should leverage @bazel/rollup (#37623)
Refactors the `ng_rollup_bundle` rule to a macro that relies on
the `@bazel/rollup` package. This means that the rule no longer
deals with custom ESM5 flavour output, but rather only builds
prodmode ES2015 output. This matches the common build output
in Angular projects, and optimizations done in CLI where
ES2015 is the default optimization input.

The motiviation for this change is:

* Not duplicating rollup Bazel rules. Instead leveraging the official
rollup rule.
* Not dealing with a third TS output flavor in Bazel.The ESM5 flavour has the
potential of slowing down local development (as it requires compilation replaying)
* Updating the rule to be aligned with current CLI optimizations.

This also _fixes_ a bug that surfaced in the old rollup bundle rule.
Code that is unused, is not removed properly. The new rule fixes this by
setting the `toplevel` flag. This instructs terser to remove unused
definitions at top-level. This matches the optimization applied in CLI
projects. Notably the CLI doesn't need this flag, as code is always
wrapped by Webpack. Hence, the unused code eliding runs by default.

PR Close #37623
2020-06-22 10:55:28 -07:00

46 lines
1.5 KiB
Python

"""Implementation of the expand_template rule """
def expand_template_impl(ctx):
substitutions = dict()
for k in ctx.attr.configuration_env_vars:
if k in ctx.var.keys():
substitutions["TMPL_%s" % k] = ctx.var[k]
for k in ctx.attr.substitutions:
substitutions[k] = ctx.expand_location(ctx.attr.substitutions[k], targets = ctx.attr.data)
ctx.actions.expand_template(
template = ctx.file.template,
output = ctx.outputs.output_name,
substitutions = substitutions,
)
"""Rule that can be used to substitute variables in a given template file."""
expand_template = rule(
implementation = expand_template_impl,
attrs = {
"configuration_env_vars": attr.string_list(
default = [],
doc = "Bazel configuration variables which should be exposed to the template.",
),
"output_name": attr.output(
mandatory = True,
doc = "File where the substituted template is written to.",
),
"substitutions": attr.string_dict(
mandatory = True,
doc = "Dictionary of substitutions that should be available to the template. Dictionary key represents the placeholder in the template.",
),
"data": attr.label_list(
doc = """Data dependencies for location expansion.""",
allow_files = True,
),
"template": attr.label(
mandatory = True,
allow_single_file = True,
doc = "File used as template.",
),
},
)