【问题标题】:MongoDB Stitch + Gatsby Buid: WebpackError: ReferenceError: self is not defined withMongoDB Stitch + Gatsby Buid: WebpackError: ReferenceError: self is not defined with
【发布时间】:2020-05-04 19:06:22
【问题描述】:

我的 react 应用是用 Gatsby 开发的。依赖“whatwg-fetch”的构建过程失败

我的应用结构基于以下项目。 https://github.com/mongodb-university/stitch-tutorial-todo-web

我在网上找到了一些提示,他们会检查窗口,但我无法让它与我的结构一起使用。 例如:https://www.gitmemory.com/issue/gatsbyjs/gatsby/8612/527732596

错误日志:

  1 | var support = {
> 2 |   searchParams: 'URLSearchParams' in self,
    | ^
  3 |   iterable: 'Symbol' in self && 'iterator' in Symbol,
  4 |   blob:
  5 |     'FileReader' in self &&



WebpackError: ReferenceError: self is not defined

- fetch.js:2 Module../node_modules/whatwg-fetch/fetch.js
  node_modules/whatwg-fetch/fetch.js:2:1

- BrowserFetchTransport.js:1 Module../node_modules/mongodb-stitch-browser-core/dist/esm/core/internal/net/BrowserFetchTransport.js
  node_modules/mongodb-stitch-browser-core/dist/esm/core/internal/net/BrowserFetchTransport.js:1:1

- index.js:1 Module../node_modules/mongodb-stitch-browser-core/dist/esm/index.js
  node_modules/mongodb-stitch-browser-core/dist/esm/index.js:1:1

- index.js:1 Module../node_modules/mongodb-stitch-browser-sdk/dist/esm/index.js
  node_modules/mongodb-stitch-browser-sdk/dist/esm/index.js:1:1`

【问题讨论】:

    标签: webpack gatsby mongodb-stitch


    【解决方案1】:

    问题在于设计用于浏览器端的whatwg-fetch 包。当 Gatsby 构建您的应用程序时,代码在 Node.js 中执行,因此上述包无法运行。

    MongoDB 为 Stitch JS SDK 分发了两个包——一个用于浏览器,一个用于服务器。理想情况下,您应该在所需的环境中同时使用它们。

    https://www.npmjs.com/package/mongodb-stitch-server-sdk

    【讨论】:

      【解决方案2】:

      我试图在 gatsby 应用程序中使用 mongodb-stitch-browser-sdk 连接到 Stitch,但构建静态 html 页面失败。 我使用 react-loadable 解决了这个问题(导入使用 react-loadable 调用 Stitch 的组件) Post.js 文件

      ...
          const LoadableComponent = Loadable({
            loader: () => import('../components/Comments'),
            loading() {
             return <div>Loading...</div>
            }
          });
      ...
      

      Comments.js 组件导入 Stitch 并连接到数据库。

      【讨论】:

        猜你喜欢
        • 2020-08-03
        • 1970-01-01
        • 2021-11-09
        • 2020-03-10
        • 2020-04-04
        • 2016-11-22
        • 2015-04-29
        • 2017-08-06
        • 2018-11-20
        相关资源
        最近更新 更多