diff --git a/contrib/nextjs/defs.bzl b/contrib/nextjs/defs.bzl index 1a67768bf..ad0d3c558 100644 --- a/contrib/nextjs/defs.bzl +++ b/contrib/nextjs/defs.bzl @@ -58,6 +58,21 @@ _next_build_config = "next.config.mjs" # A label to the rules_js/contrib config file. _next_standalone_config = Label("next.bazel.mjs") +def _nextjs_compute_chdir(): + """Compute a chdir that works for main and external workspaces. + + Returns a path under the Bazel output tree that points to this package + whether the target is in the main workspace or in an external repository. + """ + repo = native.repo_name() + pkg = native.package_name() + if repo: + if pkg: + return "external/{}/{}".format(repo, pkg) + else: + return "external/{}".format(repo) + return pkg + def nextjs( name, srcs, @@ -201,7 +216,7 @@ def nextjs_build(name, config, srcs, next_js_binary, data = [], **kwargs): args = ["build"], srcs = srcs + data + [config], out_dirs = [_next_build_out], - chdir = native.package_name(), + chdir = _nextjs_compute_chdir(), mnemonic = "NextJs", progress_message = "Compile Next.js app %{label}", **kwargs @@ -233,7 +248,7 @@ def nextjs_start(name, config, app, next_js_binary, data = [], **kwargs): tool = next_js_binary, args = ["start"], data = data + [app, config], - chdir = native.package_name(), + chdir = _nextjs_compute_chdir(), **kwargs ) @@ -262,7 +277,7 @@ def nextjs_dev(name, config, srcs, data, next_js_binary, **kwargs): tool = next_js_binary, args = ["dev"], data = srcs + data + [config], - chdir = native.package_name(), + chdir = _nextjs_compute_chdir(), **kwargs ) @@ -313,7 +328,7 @@ def nextjs_standalone_build(name, config, srcs, next_js_binary, data = [], **kwa args = ["build"], srcs = srcs + data + [":_%s.standalone_config_file" % name, config], out_dirs = [_next_build_out], - chdir = native.package_name(), + chdir = _nextjs_compute_chdir(), mnemonic = "NextJs", progress_message = "Compile Next.js standalone app %{label}", **kwargs @@ -358,7 +373,7 @@ def nextjs_standalone_server(name, app, pkg = None, data = [], **kwargs): js_binary( name = name, entry_point = ":_{}.js".format(name), - chdir = native.package_name(), + chdir = _nextjs_compute_chdir(), data = data, **kwargs ) diff --git a/contrib/nextjs/next.bazel.mjs b/contrib/nextjs/next.bazel.mjs index b3bb55047..725039fdb 100644 --- a/contrib/nextjs/next.bazel.mjs +++ b/contrib/nextjs/next.bazel.mjs @@ -12,6 +12,10 @@ if (nextjsStandaloneConfig.startsWith(process.env.BAZEL_BINDIR)) { process.env.BAZEL_BINDIR.length + 1 ) } + +// Support invocation from another workspace: strip "external//" if present +nextjsStandaloneConfig = nextjsStandaloneConfig.replace(/^external\/[^/]+\//, '') + if (!nextjsStandaloneConfig.startsWith(bazelPackage)) { throw new Error( `Next.js config must be relative to the app root: ${nextjsStandaloneConfig}`