【问题标题】:Error when building next.js app: Can't resolve 'next/head'构建 next.js 应用程序时出错:无法解析 'next/head'
【发布时间】:2019-09-23 01:30:53
【问题描述】:

在我的 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,没有修改任何文件,我得到了同样的错误。

我该如何解决这个问题?

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    我刚刚克隆了 next.js 示例,它可以与 npm run dev 以及 npm run build->npm run start 一起使用。

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

    【讨论】:

    • 有什么理由可以使用npm run build 而不是next build
    • 我没有真正的线索,但我猜它与 next 的运行方式有关? npx next build 后跟 npx next start 似乎工作正常
    • npx next start 是我为生产运行的吗?
    • 好问题!不确定,但我相信正确的方法是通过 npm 脚本来完成。
    【解决方案2】:

    解决这个问题的方法是再次重新运行这两个命令,然后您的项目将成功运行。我也遇到了这个问题,但我得到了解决方案。

    1. npm 我
    2. 纱线安装

    【讨论】:

      【解决方案3】:

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

      • node_modules
      • .next
      • 构建

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

      【讨论】:

        猜你喜欢
        • 2016-12-18
        • 2023-01-21
        • 1970-01-01
        • 2021-02-09
        • 1970-01-01
        • 1970-01-01
        • 2019-07-11
        • 2021-12-21
        • 2022-08-23
        相关资源
        最近更新 更多