添加Snipcart到盖茨比

uci*_*ska 3 reactjs snipcart gatsby

我正在尝试将Snipcart整合到Gatsby(第2版)中.

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,
}
Run Code Online (Sandbox Code Playgroud)

什么有效:

如果我创建一个div:

<a href="#" class="snipcart-edit-profile">
   Edit profile
</a>
Run Code Online (Sandbox Code Playgroud)

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

什么行不通:

当我想使用公共API时,例如,如果我打电话:

Snipcart.api.user.logout() 在一个功能.

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

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

Jea*_*lay 7

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

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

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

{
    "globals": {
        "Snipcart": false
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Snipcart对象仅在浏览器中可用,因此您应确保在Gatsby预渲染您的网站时不要调用这些功能.这意味着你应该只调用Snipcart.api.*函数以为盖茨比的浏览器API,而不是SSR或节点的API.

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

document.addEventListener('snipcart.ready', function() {
    // any Snipcart.api.* call
});
Run Code Online (Sandbox Code Playgroud)