-1

我在我的Gatsby 应用程序中使用React Intl进行国际化。该应用程序按预期运行良好,但在执行命令期间构建失败并出现错误。npm startnpm run build

代码

// gatsby-browser.js

import React from "react"
import { IntlProvider } from "react-intl"

export const wrapRootElement = ({ element }) => (
  <IntlProvider locale="en" messages={{ en: {} }}>
    {element}
  </IntlProvider>
)
// src/pages/index.js

import React from "react"
import { useIntl } from "react-intl"

const IndexPage = () => {
  const intl = useIntl()

  return <p>index.js</p>
}

export default 

错误

npm run build命令因此错误而失败。

failed Building static HTML for pages - 0.193s

 ERROR #95313 

Building static HTML failed for path "/"

See our docs page for more info on this error: https://gatsby.dev/debug-html


  74 |     if (Err === void 0) { Err = Error; }
  75 |     if (!condition) {
> 76 |         throw new Err(message);
     | ^
  77 |     }
  78 | }
  79 |


  WebpackError: [React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.
  
  - utils.js:76 
    [gatsby-starter-default]/[@formatjs]/ecma402-abstract/lib/utils.js:76:1
  
  - utils.js:6 
    [gatsby-starter-default]/[react-intl]/lib/src/utils.js:6:14
  
  - useIntl.js:6 
    [gatsby-starter-default]/[react-intl]/lib/src/components/useIntl.js:6:25
  
  - index.js:5 
    gatsby-starter-default/src/pages/index.js:5:23
  
  - extends.js:3 
    [gatsby-starter-default]/[@babel]/runtime/helpers/extends.js:3:42
  
  - extends.js:2 
    [gatsby-starter-default]/[@babel]/runtime/helpers/extends.js:2:1
  
  - extends.js:13 
    [gatsby-starter-default]/[@babel]/runtime/helpers/extends.js:13:1
  
  - static-entry.js:286 
    gatsby-starter-default/.cache/static-entry.js:286:22
  
  - index.js:72 
    [gatsby-starter-default]/[@formatjs]/fast-memoize/lib/index.js:72:1
  

not finished Caching JavaScript and CSS webpack compilation - 6.623s
not finished Caching HTML renderer compilation - 0.243s
4

1 回答 1

-1

盖茨比文档说

APIwrapPageElementwrapRootElement存在于浏览器SSR API中。您通常应该在两者中实现相同的组件,gatsby-ssr.js以便gatsby-browser.js通过 SSR 和 Node.js 生成的页面在浏览器中水合后是相同的。

解决方案

正如文档建议wrapRootElementgatsby-ssr.js和中实现的那样gatsby-browser.js,我在gatsby-ssr.js. 它就像魅力一样工作,构建并没有失败。

由于未知原因,IntlProvider 上下文SSR的构建期间丢失了。

于 2021-07-22T06:44:40.090 回答