将 Next.js v10.1.13 更新到 webpack5 时,收到警告 Can't resolve 'fsevents' in chokidar

When updating Next.js v10.1.13 to webpack5, getting warnings Can't resolve 'fsevents' in chokidar

npm install next react react-dom 和 运行 Node.js v12

创建最简单pages/index.tsx

export default function PageHome(props) {
  return <>Hello World!</>
}

(我也按照 Next.js instructions 配置了 TypeScript,但不确定这是否有所作为。)

C:\GitHub\reproduce-nextjs-webpack5-error>npm run dev
...
event - compiled successfully
<w> [webpack.cache.PackFileCacheStrategy] Caching failed for pack: Error: Can't resolve 'fsevents' in 'C:\GitHub\reproduce-nextjs-webpack5-error\node_modules\next\node_modules\chokidar'
<w> while resolving 'fsevents' in C:\GitHub\reproduce-nextjs-webpack5-error\node_modules\next\node_modules\chokidar to a directory
<w> [webpack.cache.PackFileCacheStrategy] Caching failed for pack: Error: Can't resolve 'fsevents' in 'C:\GitHub\reproduce-nextjs-webpack5-error\node_modules\next\node_modules\chokidar'
<w> while resolving 'fsevents' in C:\GitHub\reproduce-nextjs-webpack5-error\node_modules\next\node_modules\chokidar to a directory

下面的自答解决方案供未来的读者使用。

  1. 升级Node.js

  2. 删除package-lock.jsonnode_modules

  3. 运行 npm install 再一次

  4. 有效

    • 显然,当您 运行 使用较旧的 Node.js 版本时,某些东西无法安装。

    • 我的package.json看起来像

      {
        "scripts": {
          "dev": "next dev",
          "build": "next build",
          "start": "next start"
        },
        "dependencies": {
          "next": "^10.1.3",
          "react": "^17.0.2",
          "react-dom": "^17.0.2"
        },
        "devDependencies": {
          "@types/react": "^17.0.3",
          "typescript": "^4.2.4"
        }
      }
      
    • 相同的 package.json 从 Node.js v12 切换到 Node.js v15 的安装会略有不同,正如我刚才观察到的那样。这就是为什么您不仅要完成第 1 步,还要完成第 2 步和第 3 步。

之前:

C:\GitHub\reproduce-nextjs-webpack5-error>node --version
v12.4.0

C:\GitHub\reproduce-nextjs-webpack5-error>npm run dev

> @ dev C:\GitHub\reproduce-nextjs-webpack5-error
> next dev

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info  - Using webpack 5. Reason: future.webpack5 option enabled https://nextjs.org/docs/messages/webpack5
event - compiled successfully
<w> [webpack.cache.PackFileCacheStrategy] Caching failed for pack: Error: Can't resolve 'fsevents' in 'C:\GitHub\reproduce-nextjs-webpack5-error\node_modules\next\node_modules\chokidar'
<w> while resolving 'fsevents' in C:\GitHub\reproduce-nextjs-webpack5-error\node_modules\next\node_modules\chokidar to a directory

之后:

C:\GitHub\reproduce-nextjs-webpack5-error>node --version
v15.14.0

C:\GitHub\reproduce-nextjs-webpack5-error>npm run dev

> dev
> next dev

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info  - Using webpack 5. Reason: future.webpack5 option enabled https://nextjs.org/docs/messages/webpack5
event - compiled successfully
event - build page: /
wait  - compiling...
event - compiled successfully

耶!没有警告!

虽然下面有关于 nextjs@canary 未来变化的评论,但上面的例子对我来说适用于列出的版本。

我已经通过终止生产服务器上的所有节点进程解决了这个问题。