构建 next.js 应用程序时出错:无法解析 'next/head'

Error when building next.js app: Can't resolve 'next/head'

在我的 next.js 应用程序中执行 next build 时出现以下错误,在它仅使用 next(或 npm run dev)时运行良好。

错误:

$ next build
The module 'react-dom' was not found. Next.js requires that you include it in 'dependencies' of your 'package.json'. To add it, run 'npm install --save react-dom'
Creating an optimized production build ...

> Using external babel configuration
> Location: "../.babelrc"
Failed to compile.

./pages/_app.js
Module not found: Can't resolve 'next/head' in '../pages'

> Build error occurred
Error: > Build failed because of webpack errors
    at build (.../AppData/Roaming/npm/node_modules/next/dist/build/index.js:7:847)

我通过克隆 Material UI 的 next.js 示例开始我的项目,并在它看起来更新时使用它:

https://github.com/mui-org/material-ui/tree/master/examples/nextjs

但是,考虑到我的构建可能已过时或损坏,我重新克隆了 next.js 示例并做了 next build,没有修改任何文件,我得到了同样的错误.

我该如何解决这个问题?

我刚刚克隆了那个 next.js 示例,它既适用于 npm 运行 dev,也适用于 npm 运行 build->npm 运行 start。

根据您的错误判断,我会检查 "react-dom": "latest" 是否存在于您的 package.json 的依赖项中。你在克隆示例后 运行 npm install 了吗?

解决这个问题的方法是再次运行这两个命令然后你的项目就会成功运行。我也遇到了这个问题,但我找到了解决方案。

  1. npm i
  2. 纱线安装

当我将我的 nextjs 应用程序包含在 yarn 工作区中时,我 运行 遇到了类似的问题。我通过删除我的 nextjs 应用程序中的以下目录解决了这个问题:

  • node_modules
  • .下一个
  • 建设

删除它们后,我从 repo 目录中 运行 yarn 并启动 nextjs 应用程序备份,它再次工作。