Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactor & cleanup
Browse files Browse the repository at this point in the history
gregmagolan committed Mar 20, 2023
1 parent a895e7d commit 20bef7f
Showing 8 changed files with 208 additions and 198 deletions.
34 changes: 4 additions & 30 deletions docs/rules.md
Original file line number Diff line number Diff line change
@@ -5,38 +5,13 @@ Public API surface is re-exported here.
Users should not load files under "/internal"


<a id="webpack_binary"></a>

## webpack_binary

<pre>
webpack_binary(<a href="#webpack_binary-name">name</a>, <a href="#webpack_binary-node_modules">node_modules</a>)
</pre>

Create a webpack binary target from linked node_modules in the user's workspace.

The following three packages must be linked into the node_modules supplied:

webpack, webpack-cli, webpack-dev-server


**PARAMETERS**


| Name | Description | Default Value |
| :------------- | :------------- | :------------- |
| <a id="webpack_binary-name"></a>name | Unique name for the binary target | none |
| <a id="webpack_binary-node_modules"></a>node_modules | Label pointing to the linked node_modules target where webpack is linked, e.g. <code>//:node_modules</code>. | none |


<a id="webpack_bundle"></a>

## webpack_bundle

<pre>
webpack_bundle(<a href="#webpack_bundle-name">name</a>, <a href="#webpack_bundle-node_modules">node_modules</a>, <a href="#webpack_bundle-srcs">srcs</a>, <a href="#webpack_bundle-args">args</a>, <a href="#webpack_bundle-deps">deps</a>, <a href="#webpack_bundle-chdir">chdir</a>, <a href="#webpack_bundle-data">data</a>, <a href="#webpack_bundle-env">env</a>, <a href="#webpack_bundle-output_dir">output_dir</a>, <a href="#webpack_bundle-entry_point">entry_point</a>,
<a href="#webpack_bundle-entry_points">entry_points</a>, <a href="#webpack_bundle-webpack_config">webpack_config</a>, <a href="#webpack_bundle-use_execroot_entry_point">use_execroot_entry_point</a>, <a href="#webpack_bundle-supports_workers">supports_workers</a>,
<a href="#webpack_bundle-allow_execroot_entry_point_with_no_copy_data_to_bin">allow_execroot_entry_point_with_no_copy_data_to_bin</a>, <a href="#webpack_bundle-kwargs">kwargs</a>)
<a href="#webpack_bundle-entry_points">entry_points</a>, <a href="#webpack_bundle-webpack_config">webpack_config</a>, <a href="#webpack_bundle-use_execroot_entry_point">use_execroot_entry_point</a>, <a href="#webpack_bundle-supports_workers">supports_workers</a>, <a href="#webpack_bundle-kwargs">kwargs</a>)
</pre>

Runs the webpack-cli under bazel
@@ -47,7 +22,7 @@ Runs the webpack-cli under bazel
| Name | Description | Default Value |
| :------------- | :------------- | :------------- |
| <a id="webpack_bundle-name"></a>name | A unique name for this target. | none |
| <a id="webpack_bundle-node_modules"></a>node_modules | Label pointing to the linked node_modules target where webpack is linked, e.g. <code>//:node_modules</code>.<br><br>The following three packages must be linked into the node_modules supplied:<br><br> webpack, webpack-cli, webpack-dev-server | none |
| <a id="webpack_bundle-node_modules"></a>node_modules | Label pointing to the linked node_modules target where webpack is linked, e.g. <code>//:node_modules</code>.<br><br>The following packages must be linked into the node_modules supplied:<br><br> webpack, webpack-cli | none |
| <a id="webpack_bundle-srcs"></a>srcs | Non-entry point JavaScript source files from the workspace.<br><br>You must not repeat file(s) passed to entry_point/entry_points. | <code>[]</code> |
| <a id="webpack_bundle-args"></a>args | Command line arguments to pass to Webpack.<br><br>These argument passed on the command line before arguments that are added by the rule. Run <code>bazel</code> with <code>--subcommands</code> to see what Webpack CLI command line was invoked.<br><br>See the [Webpack CLI docs](https://webpack.js.org/api/cli/) for a complete list of supported arguments. | <code>[]</code> |
| <a id="webpack_bundle-deps"></a>deps | Runtime dependencies which may be loaded during compilation. | <code>[]</code> |
@@ -58,9 +33,8 @@ Runs the webpack-cli under bazel
| <a id="webpack_bundle-entry_point"></a>entry_point | The point where to start the application bundling process.<br><br>See https://webpack.js.org/concepts/entry-points/<br><br>Exactly one of <code>entry_point</code> to <code>entry_points</code> must be specified if <code>output_dir</code> is <code>False</code>. | <code>None</code> |
| <a id="webpack_bundle-entry_points"></a>entry_points | The map of entry points to bundle names.<br><br>See https://webpack.js.org/concepts/entry-points/<br><br>Exactly one of <code>entry_point</code> to <code>entry_points</code> must be specified if <code>output_dir</code> is <code>False</code>. | <code>{}</code> |
| <a id="webpack_bundle-webpack_config"></a>webpack_config | Webpack configuration file.<br><br>See https://webpack.js.org/configuration/ | <code>None</code> |
| <a id="webpack_bundle-use_execroot_entry_point"></a>use_execroot_entry_point | Use the <code>entry_point</code> script of the <code>webpack</code> <code>js_binary</code> that is in the execroot output tree instead of the copy that is in runfiles.<br><br>When set, runfiles are hoisted to the target platform when this is configured and included as target platform execroot inputs to the action.<br><br>Using the entry point script that is in the execroot output tree means that there will be no conflicting runfiles <code>node_modules</code> in the node_modules resolution path which can confuse npm packages such as next and react that don't like being resolved in multiple node_modules trees. This more closely emulates the environment that tools such as Next.js see when they are run outside of Bazel.<br><br>When True, the <code>webpack</code> <code>js_binary</code> must have <code>copy_data_to_bin</code> set to True (the default) so that all data files needed by the binary are available in the execroot output tree. This requirement can be turned off with by setting <code>allow_execroot_entry_point_with_no_copy_data_to_bin</code> to True. | <code>True</code> |
| <a id="webpack_bundle-use_execroot_entry_point"></a>use_execroot_entry_point | Use the <code>entry_point</code> script of the <code>webpack</code> <code>js_binary</code> that is in the execroot output tree instead of the copy that is in runfiles.<br><br>When set, runfiles are hoisted to the target platform when this is configured and included as target platform execroot inputs to the action.<br><br>Using the entry point script that is in the execroot output tree means that there will be no conflicting runfiles <code>node_modules</code> in the node_modules resolution path which can confuse npm packages such as next and react that don't like being resolved in multiple node_modules trees. This more closely emulates the environment that tools such as Next.js see when they are run outside of Bazel. | <code>True</code> |
| <a id="webpack_bundle-supports_workers"></a>supports_workers | Experimental! Use only with caution.<br><br>Allows you to enable the Bazel Worker strategy for this library. | <code>False</code> |
| <a id="webpack_bundle-allow_execroot_entry_point_with_no_copy_data_to_bin"></a>allow_execroot_entry_point_with_no_copy_data_to_bin | Turn off validation that the <code>webpack</code> <code>js_binary</code> has <code>copy_data_to_bin</code> set to True when <code>use_execroot_entry_point</code> is set to True.<br><br>See <code>use_execroot_entry_point</code> doc for more info. | <code>False</code> |
| <a id="webpack_bundle-kwargs"></a>kwargs | Additional arguments | none |


@@ -86,7 +60,7 @@ under the hood.
| Name | Description | Default Value |
| :------------- | :------------- | :------------- |
| <a id="webpack_devserver-name"></a>name | A unique name for this target. | none |
| <a id="webpack_devserver-node_modules"></a>node_modules | Label pointing to the linked node_modules target where webpack is linked, e.g. <code>//:node_modules</code>.<br><br>The following three packages must be linked into the node_modules supplied:<br><br> webpack, webpack-cli, webpack-dev-server | none |
| <a id="webpack_devserver-node_modules"></a>node_modules | Label pointing to the linked node_modules target where webpack is linked, e.g. <code>//:node_modules</code>.<br><br>The following packages must be linked into the node_modules supplied:<br><br> webpack, webpack-cli, webpack-dev-server | none |
| <a id="webpack_devserver-chdir"></a>chdir | Working directory to run Webpack under.<br><br>This is needed to workaround some buggy resolvers in webpack loaders, which assume that the node_modules tree is located in a parent of the working directory rather than a parent of the script with the require statement.<br><br>Note that any relative paths in your configuration may need to be adjusted so they are relative to the new working directory.<br><br>See also: https://github.com/aspect-build/rules_js/blob/main/docs/js_binary.md#js_binary-chdir | <code>None</code> |
| <a id="webpack_devserver-env"></a>env | Environment variables of the action.<br><br>Subject to <code>$(location)</code> and make variable expansion. | <code>{}</code> |
| <a id="webpack_devserver-entry_point"></a>entry_point | The point where to start the application bundling process.<br><br>See https://webpack.js.org/concepts/entry-points/<br><br>Only one of <code>entry_point</code> to <code>entry_points</code> must be specified. | <code>None</code> |
14 changes: 14 additions & 0 deletions e2e/worker/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
load("@aspect_bazel_lib//lib:write_source_files.bzl", "write_source_files")
load("@aspect_bazel_lib//lib:diff_test.bzl", "diff_test")
load("@aspect_rules_webpack//webpack:defs.bzl", "webpack_bundle")
load("@npm//:defs.bzl", "npm_link_all_packages")

@@ -17,3 +18,16 @@ write_source_files(
"expected.js_": ":bundle.js",
},
)

webpack_bundle(
name = "bundle2",
entry_point = "module.js",
node_modules = "//:node_modules",
supports_workers = True,
)

diff_test(
name = "bundles_match",
file1 = "bundle.js",
file2 = "bundle2.js",
)
3 changes: 1 addition & 2 deletions webpack/defs.bzl
Original file line number Diff line number Diff line change
@@ -17,9 +17,8 @@
Users should not load files under "/internal"
"""

load("//webpack/private:webpack_bundle.bzl", _webpack_binary = "webpack_binary", _webpack_bundle = "webpack_bundle")
load("//webpack/private:webpack_bundle.bzl", _webpack_bundle = "webpack_bundle")
load("//webpack/private:webpack_devserver.bzl", _webpack_devserver = "webpack_devserver")

webpack_binary = _webpack_binary
webpack_bundle = _webpack_bundle
webpack_devserver = _webpack_devserver
20 changes: 19 additions & 1 deletion webpack/private/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,22 +1,40 @@
load("@bazel_skylib//:bzl_library.bzl", "bzl_library")

bzl_library(
name = "webpack_binary",
srcs = ["webpack_binary.bzl"],
visibility = ["//webpack:__subpackages__"],
)

bzl_library(
name = "webpack_bundle",
srcs = ["webpack_bundle.bzl"],
visibility = ["//webpack:__subpackages__"],
deps = [
":webpack_binary",
":webpack_create_configs",
"@aspect_bazel_lib//lib:copy_file",
"@aspect_bazel_lib//lib:copy_to_bin",
"@aspect_rules_js//js:libs",
"@aspect_rules_js//js:providers",
],
)

bzl_library(
name = "webpack_create_configs",
srcs = ["webpack_create_configs.bzl"],
visibility = ["//webpack:__subpackages__"],
)

bzl_library(
name = "webpack_devserver",
srcs = ["webpack_devserver.bzl"],
visibility = ["//webpack:__subpackages__"],
deps = ["@aspect_rules_js//js:defs"],
deps = [
":webpack_binary",
":webpack_create_configs",
"@aspect_rules_js//js:defs",
],
)

exports_files([
35 changes: 35 additions & 0 deletions webpack/private/webpack_binary.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""webpack_binary helper macro"""

load("@aspect_bazel_lib//lib:directory_path.bzl", "directory_path")
load("@aspect_rules_js//js:defs.bzl", "js_binary")

def webpack_binary(
name,
node_modules,
additional_packages):
"""Create a webpack binary target from linked node_modules in the user's workspace.
Requires that `webpack` and any additional packages specified are linked into the supplied node_modules tree.
Args:
name: Unique name for the binary target
node_modules: Label pointing to the linked node_modules tree where webpack is linked, e.g. `//:node_modules`.
additional_packages: list of additional packages required. For example ["webpack-cli", "webpack-dev-server"]
"""

directory_path(
name = "{}_entrypoint".format(name),
directory = "{}/webpack/dir".format(node_modules),
path = "bin/webpack.js",
)

data = ["{}/webpack".format(node_modules)]
for p in additional_packages:
data.append("{}/{}".format(node_modules, p))

js_binary(
name = name,
data = data,
entry_point = ":{}_entrypoint".format(name),
visibility = ["//visibility:public"],
)
170 changes: 9 additions & 161 deletions webpack/private/webpack_bundle.bzl
Original file line number Diff line number Diff line change
@@ -2,12 +2,13 @@

load("@aspect_bazel_lib//lib:copy_file.bzl", "copy_file")
load("@aspect_bazel_lib//lib:copy_to_bin.bzl", "copy_files_to_bin_actions")
load("@aspect_bazel_lib//lib:directory_path.bzl", "directory_path")
load("@aspect_bazel_lib//lib:expand_make_vars.bzl", "expand_locations", "expand_variables")
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@aspect_rules_js//js:defs.bzl", "js_binary")
load("@aspect_rules_js//js:libs.bzl", "js_lib_helpers")
load("@aspect_rules_js//js:providers.bzl", "JsInfo", "js_info")
load("@bazel_skylib//lib:paths.bzl", "paths")
load(":webpack_binary.bzl", "webpack_binary")
load(":webpack_create_configs.bzl", "webpack_create_configs")

_attrs = {
"args": attr.string_list(
@@ -56,47 +57,12 @@ _attrs = {
"use_execroot_entry_point": attr.bool(
default = True,
),
"allow_execroot_entry_point_with_no_copy_data_to_bin": attr.bool(),
"_worker_js": attr.label(
allow_single_file = True,
default = "@aspect_rules_js//js/private/worker:worker.js",
),
}

_config_attrs = {
"chdir": attr.string(),
"entry_points": attr.label_keyed_string_dict(
allow_files = True,
),
"config_out": attr.output(),
"output_dir": attr.bool(),
"_webpack_config_file": attr.label(
doc = "Internal use only",
allow_single_file = [".js"],
default = Label("//webpack/private:webpack.config.js"),
),
}

def _desugar_entry_points(entry_points):
"""Converts from dict[target: string] to dict[file: string] to a validated dict[file: string] for which every key corresponds to exactly one file.
Args:
entry_points: ctx.attr.entry_points
Returns:
Dictionary mapping from file to target name.
See: https://github.com/bazelbuild/bazel/issues/5355
"""
result = {}
for ep in entry_points.items():
entry_point = ep[0]
name = ep[1]
f = entry_point.files.to_list()
if len(f) != 1:
fail("webpack_bundle entry points must provide one file, but %s has %s" % (entry_point.label, len(f)))
result[f[0]] = name
return result

def _outs(entry_points, output_dir):
"""Supply some labelled outputs in the common case of a single entry point"""
result = {}
@@ -118,41 +84,6 @@ def _relpath(ctx, file):
fail("Expected {} to be of type File, not {}".format(file, type(file)))
return paths.relativize(file.short_path, ctx.attr.chdir)

def _create_base_config_impl(ctx):
inputs = []

# Desugar entrypoints
entry_points = _desugar_entry_points(ctx.attr.entry_points).items()
entry_mapping = {}
for entry_point in entry_points:
entry_mapping[entry_point[1]] = "./%s" % _relpath(ctx, entry_point[0])

# Change source-map and mode based on compilation mode
# See: https://docs.bazel.build/versions/main/user-manual.html#flag--compilation_mode
# See: https://webpack.js.org/configuration/devtool/#devtool
compilation_mode = ctx.var["COMPILATION_MODE"]
devtool = None
mode = "development"

if compilation_mode == "fastbuild":
devtool = "eval"
elif compilation_mode == "dbg":
devtool = "eval-source-map"
elif compilation_mode == "opt":
mode = "production"

# Expand webpack config for the entry mapping
inputs.append(config)
ctx.actions.expand_template(
template = ctx.file._webpack_config_file,
output = ctx.outputs.config_out,
substitutions = {
"{ ENTRIES }": json.encode(entry_mapping),
"devtool: 'DEVTOOL',": "devtool: '{}',".format(devtool) if devtool else "",
"mode: 'MODE',": "mode: '{}',".format(mode),
},
)

def _impl(ctx):
output_sources = [getattr(ctx.outputs, o) for o in dir(ctx.outputs)]

@@ -180,8 +111,6 @@ def _impl(ctx):
}
if ctx.attr.use_execroot_entry_point:
env["JS_BINARY__USE_EXECROOT_ENTRY_POINT"] = "1"
if ctx.attr.allow_execroot_entry_point_with_no_copy_data_to_bin:
env["JS_BINARY__ALLOW_EXECROOT_ENTRY_POINT_WITH_NO_COPY_DATA_TO_BIN"] = "1"
if ctx.attr.chdir:
env["JS_BINARY__CHDIR"] = ctx.attr.chdir
entry_points_srcs = ctx.attr.entry_points.keys()
@@ -204,12 +133,12 @@ def _impl(ctx):

no_copy_bin_inputs.append(ctx.file._worker_js)

# TODO: get this path right!
path_to_execroot = ("/".join([".."] * len(ctx.label.package.split("/"))) if ctx.label.package else ".") + "/../../../"
if ctx.attr.use_execroot_entry_point:
env["JS_BINARY__ALLOW_EXECROOT_ENTRY_POINT_WITH_NO_COPY_DATA_TO_BIN"] = "1"
env["RULES_JS_WORKER"] = "/".join([".."] * len(ctx.label.package.split("/"))) + "/../../../external/burn/" + ctx.file._worker_js.short_path
env["RULES_JS_WORKER"] = path_to_execroot + ctx.file._worker_js.path
else:
env["RULES_JS_WORKER"] = "/".join([".."] * len(ctx.label.package.split("/"))) + "/../../../" + ctx.file._worker_js.short_path
env["RULES_JS_WORKER"] = path_to_execroot + ctx.file._worker_js.short_path

# Set to use a multiline param-file for worker mode
args.use_param_file("@%s", use_always = True)
@@ -313,48 +242,6 @@ _webpack_bundle = rule(
doc = "",
)

_create_base_config = rule(
implementation = _create_base_config_impl,
attrs = _config_attrs,
doc = "",
)

def webpack_create_configs(name, entry_point, entry_points, webpack_config, chdir, entry_points_mandatory):
"""
Internal use only. Not public API.
Convert the given entry point[s] rule API into a set of webpack config files.
Args:
name: the main target name this config is for
entry_point: a single entry
entry_points: multiple entries
webpack_config: a custom webpack config file
chdir: the dir webpack is run in
entry_points_mandatory: whether or not entry points must be specified
Returns:
A list of config files to pass to webpack
"""

if entry_point and entry_points:
fail("Cannot specify both entry_point and entry_points")
if entry_points_mandatory and not entry_point and not entry_points:
fail("One of entry_point or entry_points must be specified")

default_config = "%s.webpack.config.js" % name
_create_base_config(
name = "_%s_config" % name,
config_out = default_config,
entry_points = {entry_point: name} if entry_point else entry_points,
chdir = chdir,
tags = ["manual"],
)

# NOTE: generated base config should always come first as it provides sensible defaults under bazel which
# users might want to override. Also, webpack_worker uses the first webpack config path as the worker key.
return [default_config] + ([webpack_config] if webpack_config else [])

def webpack_bundle(
name,
node_modules,
@@ -370,7 +257,6 @@ def webpack_bundle(
webpack_config = None,
use_execroot_entry_point = True,
supports_workers = False,
allow_execroot_entry_point_with_no_copy_data_to_bin = False,
**kwargs):
"""Runs the webpack-cli under bazel
@@ -380,9 +266,9 @@ def webpack_bundle(
node_modules: Label pointing to the linked node_modules target where
webpack is linked, e.g. `//:node_modules`.
The following three packages must be linked into the node_modules supplied:
The following packages must be linked into the node_modules supplied:
webpack, webpack-cli, webpack-dev-server
webpack, webpack-cli
srcs: Non-entry point JavaScript source files from the workspace.
@@ -447,18 +333,10 @@ def webpack_bundle(
react that don't like being resolved in multiple node_modules trees. This more closely emulates the
environment that tools such as Next.js see when they are run outside of Bazel.
When True, the `webpack` `js_binary` must have `copy_data_to_bin` set to True (the default) so that all data files
needed by the binary are available in the execroot output tree. This requirement can be turned off with by
setting `allow_execroot_entry_point_with_no_copy_data_to_bin` to True.
supports_workers: Experimental! Use only with caution.
Allows you to enable the Bazel Worker strategy for this library.
allow_execroot_entry_point_with_no_copy_data_to_bin: Turn off validation that the `webpack` `js_binary` has `copy_data_to_bin` set to True when `use_execroot_entry_point` is set to True.
See `use_execroot_entry_point` doc for more info.
**kwargs: Additional arguments
"""

@@ -467,6 +345,7 @@ def webpack_bundle(
webpack_binary(
name = webpack_binary_target,
node_modules = node_modules,
additional_packages = ["webpack-cli"],
)

webpack_configs = webpack_create_configs(
@@ -516,36 +395,5 @@ def webpack_bundle(
webpack_worker_target_cfg = webpack_worker_binary_target,
use_execroot_entry_point = use_execroot_entry_point,
supports_workers = supports_workers,
allow_execroot_entry_point_with_no_copy_data_to_bin = allow_execroot_entry_point_with_no_copy_data_to_bin,
**kwargs
)

def webpack_binary(name, node_modules):
"""Create a webpack binary target from linked node_modules in the user's workspace.
The following three packages must be linked into the node_modules supplied:
webpack, webpack-cli, webpack-dev-server
Args:
name: Unique name for the binary target
node_modules: Label pointing to the linked node_modules target where
webpack is linked, e.g. `//:node_modules`.
"""

directory_path(
name = "{}_entrypoint".format(name),
directory = "{}/webpack/dir".format(node_modules),
path = "bin/webpack.js",
)

js_binary(
name = name,
data = [
"{}/webpack".format(node_modules),
"{}/webpack-cli".format(node_modules),
"{}/webpack-dev-server".format(node_modules),
],
entry_point = ":{}_entrypoint".format(name),
visibility = ["//visibility:public"],
)
120 changes: 120 additions & 0 deletions webpack/private/webpack_create_configs.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
"""webpack_create_configs rule"""

load("@bazel_skylib//lib:paths.bzl", "paths")

_config_attrs = {
"chdir": attr.string(),
"entry_points": attr.label_keyed_string_dict(
allow_files = True,
),
"config_out": attr.output(),
"output_dir": attr.bool(),
"_webpack_config_file": attr.label(
doc = "Internal use only",
allow_single_file = [".js"],
default = Label("//webpack/private:webpack.config.js"),
),
}

def _desugar_entry_points(entry_points):
"""Converts from dict[target: string] to dict[file: string] to a validated dict[file: string] for which every key corresponds to exactly one file.
Args:
entry_points: ctx.attr.entry_points
Returns:
Dictionary mapping from file to target name.
See: https://github.com/bazelbuild/bazel/issues/5355
"""
result = {}
for ep in entry_points.items():
entry_point = ep[0]
name = ep[1]
f = entry_point.files.to_list()
if len(f) != 1:
fail("webpack_bundle entry points must provide one file, but %s has %s" % (entry_point.label, len(f)))
result[f[0]] = name
return result

def _relpath(ctx, file):
"""Path from the working directory to a given file object"""
if type(file) != "File":
fail("Expected {} to be of type File, not {}".format(file, type(file)))
return paths.relativize(file.short_path, ctx.attr.chdir)

def _create_base_config_impl(ctx):
inputs = []

# Desugar entrypoints
entry_points = _desugar_entry_points(ctx.attr.entry_points).items()
entry_mapping = {}
for entry_point in entry_points:
entry_mapping[entry_point[1]] = "./%s" % _relpath(ctx, entry_point[0])

# Change source-map and mode based on compilation mode
# See: https://docs.bazel.build/versions/main/user-manual.html#flag--compilation_mode
# See: https://webpack.js.org/configuration/devtool/#devtool
compilation_mode = ctx.var["COMPILATION_MODE"]
devtool = None
mode = "development"

if compilation_mode == "fastbuild":
devtool = "eval"
elif compilation_mode == "dbg":
devtool = "eval-source-map"
elif compilation_mode == "opt":
mode = "production"

# Expand webpack config for the entry mapping
inputs.append(config)
ctx.actions.expand_template(
template = ctx.file._webpack_config_file,
output = ctx.outputs.config_out,
substitutions = {
"{ ENTRIES }": json.encode(entry_mapping),
"devtool: 'DEVTOOL',": "devtool: '{}',".format(devtool) if devtool else "",
"mode: 'MODE',": "mode: '{}',".format(mode),
},
)

_create_base_config = rule(
implementation = _create_base_config_impl,
attrs = _config_attrs,
doc = "",
)

def webpack_create_configs(name, entry_point, entry_points, webpack_config, chdir, entry_points_mandatory):
"""
Internal use only. Not public API.
Convert the given entry point[s] rule API into a set of webpack config files.
Args:
name: the main target name this config is for
entry_point: a single entry
entry_points: multiple entries
webpack_config: a custom webpack config file
chdir: the dir webpack is run in
entry_points_mandatory: whether or not entry points must be specified
Returns:
A list of config files to pass to webpack
"""

if entry_point and entry_points:
fail("Cannot specify both entry_point and entry_points")
if entry_points_mandatory and not entry_point and not entry_points:
fail("One of entry_point or entry_points must be specified")

default_config = "%s.webpack.config.js" % name
_create_base_config(
name = "_%s_config" % name,
config_out = default_config,
entry_points = {entry_point: name} if entry_point else entry_points,
chdir = chdir,
tags = ["manual"],
)

# NOTE: generated base config should always come first as it provides sensible defaults under bazel which
# users might want to override. Also, webpack_worker uses the first webpack config path as the worker key.
return [default_config] + ([webpack_config] if webpack_config else [])
10 changes: 6 additions & 4 deletions webpack/private/webpack_devserver.bzl
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Webpack devserver rule definition."""

load("@aspect_rules_js//js:defs.bzl", "js_run_devserver")
load(":webpack_bundle.bzl", _webpack_binary = "webpack_binary", _webpack_create_configs = "webpack_create_configs")
load(":webpack_binary.bzl", "webpack_binary")
load(":webpack_create_configs.bzl", "webpack_create_configs")

def webpack_devserver(
name,
@@ -27,7 +28,7 @@ def webpack_devserver(
node_modules: Label pointing to the linked node_modules target where
webpack is linked, e.g. `//:node_modules`.
The following three packages must be linked into the node_modules supplied:
The following packages must be linked into the node_modules supplied:
webpack, webpack-cli, webpack-dev-server
@@ -85,7 +86,7 @@ def webpack_devserver(
if chdir:
unwind_chdir_prefix = "/".join([".."] * len(chdir.split("/"))) + "/"

webpack_configs = _webpack_create_configs(
webpack_configs = webpack_create_configs(
name = name,
entry_point = entry_point,
entry_points = entry_points,
@@ -104,9 +105,10 @@ def webpack_devserver(

webpack_binary_target = "_{}_webpack_binary".format(name)

_webpack_binary(
webpack_binary(
name = webpack_binary_target,
node_modules = node_modules,
additional_packages = ["webpack-cli", "webpack-dev-server"],
)

js_run_devserver(

0 comments on commit 20bef7f

Please sign in to comment.