在 VS Code Remote Container/devcontainer 中使用 Next.js 开发模式快速刷新

Fast Refresh with Next.js development mode in VS Code Remote Container/devcontainer

我无法让 Next.js' 快速刷新功能与 VS Code Remote Container 一起使用。我可以 运行 npm run dev 并在我机器上的本地主机上看到应用程序 运行ning,因此容器工作正常 - 只有快速刷新根本没有效果。

Next.js版本:v11.0.1

我用 Windows 10 和 Ubuntu 20.04(在 WSL 2 上)都试过了。


我已经尝试在 next.config.js 中使用自定义 webpack 中间件,就像这样(参见 https://github.com/vercel/next.js/issues/2179#issuecomment-316568536):

module.exports = {
    webpackDevMiddleware: (config) => {
        // Solve compiling problem via vagrant
        config.watchOptions = {
            poll: 1000,   // Check for changes every second
            aggregateTimeout: 300,   // delay before rebuilding
        };
        return config;
    },
};

...这将触发代码更改的重新编译,但浏览器不会更新。

此外,对“HMR”的请求失败:


如何重现:

  1. 安装 Remote Containers extension
  2. 打开任何新文件夹
  3. 打开命令面板和type/select“远程容器:在容器中重建并重新打开”
  4. Type/select "Node.js"
  5. Type/select版本“16”并等待容器启动
  6. 转到 .devcontainer 文件夹并打开 devcontainer.json
  7. 通过添加 "forwardPorts": [3002], 编辑配置以使应用程序在您的主机上可用并重建容器(通过 VS Code 的命令面板)
  8. 从终端安装 Next.js,例如:npx create-next-app --use-npm --example with-typescript-eslint-jest my-app
  9. 将所有文件从 my-app 移动到您的 VS Code 项目根文件夹。必须这样做,因为 create-next-app 无法通过 . 安装在项目根文件夹中,因为已经存在 .devcontainer 文件夹。
  10. 可选:创建 next.config.js 并添加 Webpack dev 中间件的代码片段,如上所示
  11. 编辑 package.json 脚本以使用特定端口:"dev": "next dev -p 3002",(或者,如果您使用 WSL 2:next dev -p 3002 -H ::
  12. 从终端启动应用程序npm run dev
  13. http://localhost:3002
  14. 打开浏览器
  15. 正在显示该应用程序。在代码中进行更改 -> 即使是重新编译的应用程序也不会在浏览器中显示更改。不过,在浏览器中重新加载页面将显示更改。

对于 Create React App,有一个 advanced configuration without ejecting(称为 CHOKIDAR_USEPOLLING),这使得他们的快速刷新与远程容器一起工作。


早些时候我 created a feature request,但也许有人已经设法在 configuration/setup?

我注意到这个问题和 Next.js (v12.1.6) 的当前版本之间发生了很大变化。

我刚刚又试了一次,似乎终于奏效了!

我打算更改我的 Next.js 项目以使用 devcontainers,也许其他东西不起作用,但至少对于 Fast Refresh,这个话题已经解决了。


如果您按照上述步骤操作,最基本的设置应该如下所示。它基于默认的“Node.js v16”devcontainer 预配置。 您甚至不再需要 forwardPorts

// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.234.0/containers/javascript-node
{
    "name": "My project",
    "build": {
        "dockerfile": "Dockerfile",
        // Update 'VARIANT' to pick a Node version: 18, 16, 14.
        // Append -bullseye or -buster to pin to an OS version.
        // Use -bullseye variants on local arm64/Apple Silicon.
        "args": { "VARIANT": "16" }
    },
    "settings": {},
    "extensions": [
        "dbaeumer.vscode-eslint"
    ],
    // Use 'forwardPorts' to make a list of ports inside the container available locally.
    // "forwardPorts": [],
    // Use 'postCreateCommand' to run commands after the container is created.
    // "postCreateCommand": "yarn install",
    // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
    "remoteUser": "node"
}