rules_nodejs icon indicating copy to clipboard operation
rules_nodejs copied to clipboard

Example of next.js build-time prerendering

Open alexeagle opened this issue 6 years ago • 18 comments

Next.js docs for prerendering: https://nextjs.org/learn/basics/data-fetching/two-forms

alexeagle avatar Jul 22 '20 21:07 alexeagle

cc @elliottsj I see you've been down this road before https://github.com/vercel/next.js/issues/9588

alexeagle avatar Jul 22 '20 22:07 alexeagle

Unfortunately I didn't get too far since I ended up blocked by that issue, and ended up not using Bazel due to other circumstances as well.

This is what I tried without success:

# This doesn't work; results in this error:
#   > Build error occurred
#   Error: > Build directory is not writeable. https://err.sh/zeit/next.js/build-dir-not-writeable
# This is because the next.config.js file isn't picked up by the Next.js CLI, because it's not found
# in the working directory.
next(
    name = "next",
    args = [
        "build",
        "$(location src)",
        # Normally we'd pass in the output dir as a "$@" argument like below.
        # But the Next.js CLI doesn't accept args for the output dir, so this isn't possible.
        # Instead, we're hard-coding the output dir in next.config.js for now.
        # "$@",
    ],
    data = [
        "next.config.js",
        "src/.",
        "@npm//:node_modules",
    ],
    output_dir = True,
)

elliottsj avatar Jul 23 '20 17:07 elliottsj

@alexeagle FWIW we (+ @elliottsj) use Nx to manage our monorepo. They do have some sort of Bazel support planned.

I know that the folks over at Nrwl have been involved with you in the past. They might have some ideas or working examples of NextJS and Bazel.

RamaneekGill avatar Jul 23 '20 18:07 RamaneekGill

my setup is a little different. My project is housing a polyglot lang. mono-repos. I was able to get the build to complete without write_chdir_script. But, the generated .next/* files are missing in my run file. This is probably because of write_chdir_script not executing?

next(
    name = ".next",
    args = [
        "build",
        "./src/js/hello-world",
    ],
    data = glob([
        "components/*",
        "pages/**",
        "public/**",
        "styles/*",
    ]) + [
        "//:package.json",
    ],
    output_dir = True,
)

next(
    name = ".next.start",
    args = [
        "start",
        "./src/js/hello-world",
    ],
    data = [":.next"],
)
% yarn build                                   
yarn run v1.22.4
$ bazelisk build //src/js/hello-world:.next
INFO: Build option --legacy_external_runfiles has changed, discarding analysis cache.
INFO: Analyzed target //src/js/hello-world:.next (1 packages loaded, 16178 targets configured).
INFO: Found 1 target...
INFO: From Action src/js/hello-world/.next:
Creating an optimized production build...

Compiled successfully.

Automatically optimizing pages...

Page                                                           Size     First Load JS
┌ ○ /                                                          3.42 kB        61.3 kB
├   └ css/80ef9a32b2f9e4d03d0b.css                             660 B
├ ○ /404                                                       3.46 kB        61.3 kB
└ λ /api/hello                                                 0 B            57.9 kB
+ First Load JS shared by all                                  57.9 kB
  ├ chunks/f6078781a05fe1bcb0902d23dbbb2662c8d200b3.3bec96.js  10.2 kB
  ├ chunks/framework.9cd2c6.js                                 40 kB
  ├ chunks/main.126e78.js                                      6.71 kB
  ├ chunks/pages/_app.ce79c4.js                                258 B
  └ chunks/webpack.488dc2.js                                   751 B

λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
○  (Static)  automatically rendered as static HTML (uses no initial props)
●  (SSG)     automatically generated as static HTML + JSON (uses getStaticProps)

Redirects

┌ source: /:path+/
├ destination: /:path+
└ permanent: true
 

Target //src/js/hello-world:.next up-to-date:
  dist/bin/src/js/hello-world/.next
INFO: Elapsed time: 11.159s, Critical Path: 10.54s
INFO: 1 process: 1 darwin-sandbox.
INFO: Build completed successfully, 2 total actions
✨  Done in 11.52s.

I was able to run but without output.

filegroup(
    name = "sources",
    srcs = glob(
        include = ["**/*.*"],
        exclude = EXCLUDE_PATTERNS,
    ),
)

nodejs_binary(
    name = ".next",
    data = [
        ":sources",
        "//:package.json",
        "@npm//:node_modules",
    ],
    args = ["./src/js/hello-world"],
    entry_point = "@npm//:node_modules/next/dist/bin/next",
    install_source_map_support = False,
)

theofanisM avatar Aug 09 '20 13:08 theofanisM

I'll record my setup which little different from both here which can be got expected output.

# My custom rule
load(":next_config_js.bzl", "next_config_js")

next_config_js(
    name = "next.config",
    template = "//:next.config.js.tpl",
)

load("@build_bazel_rules_nodejs//:index.bzl", "npm_package_bin")

npm_package_bin(
    name = "dist",
    args = [
        "build",
    ],
    tool = "@npm//next/bin:next",
    output_dir = True,
    data = [
        # If npm_package_bin provides a interface transitive_deps, this target can access next.config.js which //:next.config build.
        # //:next.config
        "//:next.config.js",
        "//:pages/index.jsx",
        "//:package.json",
        "@npm//:node_modules",
    ],
)

As @alexeagle and @elliottsj have pointed out, it seems to be common in Bazel to pass the output directory from the CLI, but the Next.js CLI doesn't have such interfaces. So, I tried to generate next.config.js dynamically, which can configure distDir despite the CLI interface.

The following is the sample repository. https://github.com/kogai/exapmle-bazel-nextjs

It specifies an output directory by executing a custom-Bazel-rule that replaces the distDir in next.config.js.tpl by building //:next.config target.

However, //:dist target can't access the generated next.config.js even though //:next.config has been set to data parameter of npm_package_bin. This is why I need a workaround to copy from bazel-bin/next.config.js to repository root which outside of the bazel's sandbox, as I wrote in README.md.

According to the documentation,

similar to genrule.srcs may also include targets that produce or reference npm packages which are needed by the tool

https://github.com/bazelbuild/rules_nodejs/blob/stable/docs/Built-ins.md#data-4

Does this explain the different nature of deps? Or, perhaps if #1504 is merged and the //:next.config can be set as transitive_deps, this problem might be solved.

kogai avatar Aug 19 '20 03:08 kogai

This issue has been automatically marked as stale because it has not had any activity for 60 days. It will be closed if no further activity occurs in two weeks. Collaborators can add a "cleanup" or "need: discussion" label to keep it open indefinitely. Thanks for your contributions to rules_nodejs!

github-actions[bot] avatar Oct 19 '20 01:10 github-actions[bot]

This issue was automatically closed because it went two weeks without a reply since it was labeled "Can Close?"

github-actions[bot] avatar Nov 03 '20 01:11 github-actions[bot]

For anyone having trouble here, I was able to get this working with the auto-generated next-cli Bazel rules by using copy_to_bin to get around Next's output directory constraints.

load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin")
load("@npm//next:index.bzl", "next")

# Next.js doesn't allow its build output to be written anywhere outside of the
# source directory, so we copy all of the source files over into the bin folder
# and run next on the source there. That way, the output will be written there
# and we can return it as our rule output.

copy_to_bin(
    name = "bin_src",
    srcs = [
        "pages/index.js",
    ],
)

next(
    name = "next_build",
    outs = [".next"],
    args = ["build $(RULEDIR)"],
    data = [":bin_src"],
)

next(
    name = "build",
    outs = ["dist"],
    args = [
        "export $(RULEDIR)",
        "-o $(@)",
    ],
    data = [":next_build"],
)

ofagbemi avatar Jan 27 '21 17:01 ofagbemi

Working example with copy_to_bin and @npm//next:index.bzl: flolu/nextjs-bazel

But importing global CSS styles into pages/_app.js causes this error:

Global CSS cannot be imported from files other than your Custom <App>. Please move all global CSS imports to pages/_app.js. Or convert the import to Component-Level CSS (CSS Modules).

The issue: https://github.com/flolu/nextjs-bazel/issues/1

Any ideas for this?

flolu avatar Mar 28 '21 19:03 flolu

After some debugging it turns out that this if is not triggered, meaning ctx.customAppFile is null.

Here is a log output of ctx when building with Bazel:

{
  ctx: {
    rootDirectory: '/home/flo/.cache/bazel/_bazel_flo/e959037946bf226f3b911fa40ec62d93/sandbox/linux-sandbox/85/execroot/nextjs-bazel/bazel-out/k8-fastbuild/bin',
    customAppFile: null,
    // ...
  }
}

flolu avatar Mar 30 '21 15:03 flolu

After some more debugging, I found the problem: This if statement throws an error

Error: EACCES: permission denied, access '/home/flo/.cache/bazel/_bazel_flo/e959037946bf226f3b911fa40ec62d93/sandbox/linux-sandbox/186/execroot/nextjs-bazel/bazel-out/k8-fastbuild/bin/pages/_app.tsx'

If I patch Next.js to ignore this error, everything works fine! Is there any way to prevent this error when building with Bazel?

flolu avatar Mar 31 '21 07:03 flolu

Nice digging @flolu ! The workaround would be to run without the Bazel sandbox so the files have the original write permissions.

But I think we should make a PR to next.js to fix that assertion. They should be able to operate on a read-only file tree (there are other uses for this like when sources get mounted from a network filesystem in some CI systems). I think they would accept it since there are some ppl over there working on Bazel adoption.

alexeagle avatar Mar 31 '21 21:03 alexeagle

I've tried to add tags = ["no-sandbox"] but it does not seem to disable the sandbox. How can I disable sandbox for certain rules? Adding --spawn_strategy=local seems to run it outside the sandbox.

Strangely it still throws this error when buildilng.

[Error: EACCES: permission denied, access '/home/flo/.cache/bazel/_bazel_flo/e959037946bf226f3b911fa40ec62d93/execroot/nextjs-bazel/bazel-out/k8-fastbuild/bin/pages/_app.tsx']

But it solved another problem I've had: I want to use Tailwind for styling. CSS purging did not work when running in the sandbox, but it now does.


So for now the best option might be to patch Next.js to ignore the error?!

next+10.0.9.patch

diff --git a/node_modules/next/dist/build/is-writeable.js b/node_modules/next/dist/build/is-writeable.js
index eb88210..7b5fe8c 100644
--- a/node_modules/next/dist/build/is-writeable.js
+++ b/node_modules/next/dist/build/is-writeable.js
@@ -1,2 +1,2 @@
-"use strict";exports.__esModule=true;exports.isWriteable=isWriteable;var _fs=_interopRequireDefault(require("fs"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}async function isWriteable(directory){try{await _fs.default.promises.access(directory,(_fs.default.constants||_fs.default).W_OK);return true;}catch(err){return false;}}
+"use strict";exports.__esModule=true;exports.isWriteable=isWriteable;var _fs=_interopRequireDefault(require("fs"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}async function isWriteable(directory){try{await _fs.default.promises.access(directory,(_fs.default.constants||_fs.default).W_OK);return true;}catch(err){if(err.errno===-13&&err.path.includes('/bazel-out/'))return true;return false;}}
 //# sourceMappingURL=is-writeable.js.map
\ No newline at end of file

flolu avatar Apr 01 '21 06:04 flolu

This issue has been automatically marked as stale because it has not had any activity for 90 days. It will be closed if no further activity occurs in two weeks. Collaborators can add a "cleanup" or "need: discussion" label to keep it open indefinitely. Thanks for your contributions to rules_nodejs!

github-actions[bot] avatar Jul 19 '21 02:07 github-actions[bot]

This issue was automatically closed because it went two weeks without a reply since it was labeled "Can Close?"

github-actions[bot] avatar Aug 03 '21 02:08 github-actions[bot]

I have this error.

yarn run v1.22.10
$ bazel build //...
INFO: Invocation ID: 52a3e0b2-0042-46a6-9eec-5fdf8d181ed3
INFO: Analyzed 9 targets (2 packages loaded, 13 targets configured).
INFO: Found 9 targets...
ERROR: C:/users/xnerh/projects/wexond-old/bazel-test/frontend/website/BUILD:13:5: Action frontend/website/.next failed: (Exit 1): next.bat failed: error executing command bazel-out/host/bin/external/npm/next/bin/next.bat build bazel-out/x64_windows-fastbuild/bin/frontend/website ... (remaining 1 argument(s) skipped)> Build error occurred
[Error: EPERM: operation not permitted, open 'C:\users\xnerh\_bazel_xnerh\d2buhs2e\execroot\init\bazel-out\x64_windows-fastbuild\bin\frontend\website\next-env.d.ts'] {  errno: -4048,
  code: 'EPERM',  syscall: 'open',
  path: 'C:\\users\\xnerh\\_bazel_xnerh\\d2buhs2e\\execroot\\init\\bazel-out\\x64_windows-fastbuild\\bin\\frontend\\website\\next-env.d.ts'
}

xnerhu avatar Aug 28 '21 23:08 xnerhu

@gregmagolan happens to be working on this for a client, I believe

alexeagle avatar Aug 30 '21 13:08 alexeagle

No longer in scope for rules_nodejs which only supplies the Node.js toolchain as of v6.0.0.

Downstream canonical JavaScript + Node.js ruleset is now https://github.com/aspect-build/rules_js.

gregmagolan avatar Jun 08 '24 21:06 gregmagolan