首页 > 解决方案 > 将 Snipcart 添加到 Gatsby

问题描述

我正在尝试将 Snipcart 集成到 Gatsby (v2) 中。

我像这样编辑html.js文件:

import React from "react"
import PropTypes from "prop-types"

export default class HTML extends React.Component {
  render() {
    return (
      <html {...this.props.htmlAttributes}>
        <head>
          <meta charSet="utf-8" />
          <meta httpEquiv="x-ua-compatible" content="ie=edge" />
          <meta
            name="viewport"
            content="width=device-width, initial-scale=1, shrink-to-fit=no"
          />
          {this.props.headComponents}

          {/* Snipcart */}
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
          <script src="https://cdn.snipcart.com/scripts/2.0/snipcart.js" id="snipcart" data-api-key="UF45pIjZjAtZWJkYS00MGEwLWIxZWEtNjljZThjNTRiNjA4NjM2NDg1MzAzMzQyNfDrr48"></script>
          <link href="https://cdn.snipcart.com/themes/2.0/base/snipcart.min.css" type="text/css" rel="stylesheet" />

        </head>
        <body {...this.props.bodyAttributes}>
          {this.props.preBodyComponents}
          <div
            key={`body`}
            id="___gatsby"
            dangerouslySetInnerHTML={{ __html: this.props.body }}
          />
          {this.props.postBodyComponents}

        </body>
      </html>
    )
  }
}

HTML.propTypes = {
  htmlAttributes: PropTypes.object,
  headComponents: PropTypes.array,
  bodyAttributes: PropTypes.object,
  preBodyComponents: PropTypes.array,
  body: PropTypes.string,
  postBodyComponents: PropTypes.array,
}

什么有效:

如果我创建一个 div:

<a href="#" class="snipcart-edit-profile">
   Edit profile
</a>

Snipcart 工作并在单击时打开用户配置文件。

什么不起作用:

当我想使用公共 API 时,例如,如果我调用:

Snipcart.api.user.logout()在一个函数中。

=> error 'Snipcart' is not defined no-undef

如何在我的所有应用程序中拥有全局 Snipcart 对象?

标签: reactjsgatsbysnipcart

解决方案


no-undef是一个 linter 错误,而不是运行时错误。因此,它并不表示您的代码运行时 Snipcart 不可用。

如果它不可用,您将在浏览器的控制台中收到此错误:ReferenceError: Snipcart is not defined

如果你正在使用eslint,你可以在你的 eslint 配置中添加一个像这样的全局变量:

{
    "globals": {
        "Snipcart": false
    }
}

或者,您可以在使用 Snipcart API 的文件中添加注释:/* global Snipcart:false */


Snipcart对象仅在浏览器中可用,因此您应确保在 Gatsby 预渲染您的网站时不要调用这些函数。这意味着您应该只调用Gatsby 的浏览器 API而不是 SSR 或 Node API的Snipcart.api.*函数。

此外,为了确保您仅在脚本完全加载后才调用 Snipcart 的 API,您可以检查snipcart.ready事件

document.addEventListener('snipcart.ready', function() {
    // any Snipcart.api.* call
});

推荐阅读