blob: be6826c2f063651840fb9b9f745016661ce5a3e3 [file] [log] [blame]
Philipp Schrader87277f42022-01-01 07:45:12 -08001load("@build_bazel_rules_nodejs//:providers.bzl", "JSModuleInfo")
2load("@npm//@bazel/rollup:index.bzl", upstream_rollup_bundle = "rollup_bundle")
3load("@npm//@bazel/terser:index.bzl", "terser_minified")
4
5def rollup_bundle(name, deps, visibility = None, **kwargs):
6 """Calls the upstream rollup_bundle() and exposes a .min.js file.
7
8 Legacy version of rollup_bundle() used to provide the .min.js file. This
9 wrapper provides the same interface by explicitly exposing a .min.js file.
10 """
11 upstream_rollup_bundle(
12 name = name,
13 visibility = visibility,
14 deps = deps + [
15 "@npm//@rollup/plugin-node-resolve",
16 ],
17 config_file = "//:rollup.config.js",
18 link_workspace_root = True,
19 **kwargs
20 )
21
22 terser_minified(
23 name = name + "__min",
24 src = name + ".js",
25 )
26
27 # Copy the __min.js file (a declared output inside the rule) so that it's a
28 # pre-declared output and publicly visible. I.e. via attr.output() below.
29 _expose_minified_js(
30 name = name + "__min_exposed",
31 src = ":%s__min" % name,
32 out = name + ".min.js",
33 visibility = visibility,
34 )
35
36def _expose_minified_js_impl(ctx):
37 """Copies the .min.js file in order to make it publicly accessible."""
38 sources = ctx.attr.src[JSModuleInfo].sources.to_list()
39 min_js = None
40 for src in sources:
41 if src.basename.endswith("__min.js"):
42 min_js = src
43 break
44
45 if min_js == None:
46 fail("Couldn't find .min.js in " + str(ctx.attr.src))
47
48 ctx.actions.run(
49 inputs = [min_js],
50 outputs = [ctx.outputs.out],
51 executable = "cp",
52 arguments = [min_js.path, ctx.outputs.out.path],
53 )
54
55_expose_minified_js = rule(
56 implementation = _expose_minified_js_impl,
57 attrs = {
58 "src": attr.label(providers = [JSModuleInfo]),
59 "out": attr.output(mandatory = True),
60 },
61)
Philipp Schrader684a8e82022-02-25 17:39:28 -080062
63# Some rules (e.g. babel()) do not expose their files as runfiles. So we need
64# to do this step manually.
65def _turn_files_into_runfiles_impl(ctx):
66 files = ctx.attr.files.files
67 return [DefaultInfo(
68 files = files,
69 runfiles = ctx.runfiles(transitive_files = files),
70 )]
71
72turn_files_into_runfiles = rule(
73 implementation = _turn_files_into_runfiles_impl,
74 attrs = {
75 "files": attr.label(
76 mandatory = True,
77 doc = "The target whose files should be turned into runfiles.",
78 ),
79 },
80)