Skip to content

Instantly share code, notes, and snippets.

@alexeagle
Created September 20, 2019 22:59
Show Gist options
  • Save alexeagle/f4160b15aa1d0be7b3c50b78745bd31d to your computer and use it in GitHub Desktop.
Save alexeagle/f4160b15aa1d0be7b3c50b78745bd31d to your computer and use it in GitHub Desktop.
load("@npm_bazel_rollup//:index.bzl", "rollup_bundle")
load("@npm_bazel_terser//:index.bzl", "terser_minified")
load("@npm//@babel/cli:index.bzl", "babel")
# TODO(alexeagle): promote web_package rule to the public API
load("@build_bazel_rules_nodejs//internal/web_package:web_package.bzl", "web_package")
def differential_loading(name, entry_point, srcs):
"Common workflow to serve native ESModules to modern browsers"
rollup_bundle(
name = name + "_chunks",
srcs = srcs,
entry_points = {
entry_point: "index",
},
output_dir = True,
)
# For older browsers, we'll transform the output chunks to es5 + systemjs loader
babel(
name = name + "_chunks_es5",
data = [
name + "_chunks",
"es5.babelrc",
"@npm//@babel/preset-env",
],
out_dir = name + "_chunks_es5",
args = [
"$(location %s_chunks)" % name,
"--config-file",
"$(location es5.babelrc)",
"--out-dir",
"$@",
],
)
# Run terser against both modern and legacy browser chunks
terser_minified(
name = name + "_chunks_es5.min",
src = name + "_chunks_es5",
)
terser_minified(
name = name + "_chunks.min",
src = name + "_chunks",
)
web_package(
name = name,
assets = [
"styles.css",
],
data = [
"favicon.png",
name + "_chunks.min",
name + "_chunks_es5.min",
],
index_html = "index.html",
)
@alexeagle
Copy link
Author

alexeagle commented Sep 20, 2019

index.html would then be

<html>
    <head>
        <title>rules_nodejs webapp example</title>
        <link rel="icon" href="/favicon.png">
        <!-- CSS will be linked here from web_package#assets -->
    </head>
    <script type="module" src="/app_chunks.min/index.js"></script>
    <script nomodule="" src="/app_chunks_es5.min/index.js"></script>
</html>

and you build and serve the app with

load(":differential_loading.bzl", "differential_loading")
load("@npm//http-server:index.bzl", "http_server")

differential_loading(
    name = "app",
    entry_point = "index.js",
    srcs = glob(["*.js"]),
)

http_server(
    name = "server",
    data = [":app"],
    templated_args = ["app"],
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment