如何在Gatsby.js项目中包含jQuery?

Jon*_*mar 4 jquery reactjs gatsby jamstack

我已经尝试了gatsby.js一段时间,除此问题外,其他一切都进行得很好,我无法将jQuery脚本包含到应用程序中,以便在渲染gatsby应用程序后加载它,我将包含的脚本标签该html.js文件并加载它,但似乎代码是在react将内容呈现到我尝试使用的屏幕上之前执行的simple-load-script,以及将其包含componentDidMounthtml.js应用程序的方法上。但是没有运气,这是我html.js文件的源代码:

html.js

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

export default class HTML extends React.Component {
  componentDidMount() {
    console.log('hello world');
  }
  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}
        </head>
        <body>
          {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)

如您所见,我替换了将componentDidMount()方法写出到控制台的方法,但并没有阻止该方法执行的功能。

如果有任何经验,请分享,谢谢。

小智 21

将 jQuery 添加到 Gatsby 项目的另一种方法 - 使用 gatsby-ssr.js 和 gatsby-browser.js:

将 jQuery 添加到 gatsby-ssr.js

如果您还没有 gatsby-ssr.js,则需要为您的根创建一个 gatsby-ssr.js。

const React = require("react")

export const onRenderBody = ({ setHeadComponents }, pluginOptions) => {
  setHeadComponents([
    <script
      src="https://code.jquery.com/jquery-3.4.1.min.js"
      integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
      crossOrigin="anonymous">
    </script>,
  ])
}
Run Code Online (Sandbox Code Playgroud)

它将把你的脚本标签放在顶部注意:如果你正在运行一个开发环境,你需要再次运行它以使 gatsby-ssr.js 工作

将您的代码添加到 gatsby-browser.js

如果您还没有 gatsby-browser.js,则需要在根目录中创建一个 gatsby-browser.js。这将是您的代码的地方:

const $ = require("jquery")

export const onInitialClientRender = () => {
  $(document).ready(function () {
    console.log("The answer is don't think about it!")
  });
}
Run Code Online (Sandbox Code Playgroud)

此方法将您的代码放入 common.js 您也可以使用其他 API 来运行您的代码:Gatsby Browser API doc

免责声明

它有点老套,一般来说,真的不建议将 jQuery 与 Gatsby 一起使用,但为了快速修复,它工作得很好。

此外,Gatsby 指南不推荐 html.js:

当 gatsby-ssr.js 中无法使用适当的 API 时,自定义 html.js 是一种变通解决方案。考虑使用 onRenderBody 或 onPreRenderHTML 代替上述方法。作为进一步的考虑,在 Gatsby 主题中不支持自定义 html.js。请改用提到的 API 方法。


Der*_*yen 11

如果要将jQuery作为外部(从CDN加载)添加到gastby,则有些棘手。您需要:

  • 将jQuery CDN添加到 html.js
  • 添加external到Webpack配置中gatsby-node.js

将jQuery添加到 html.js

您可能已经做到了:cp .cache/default-html.js src/html.js,然后添加

// src/html.js
<head>
  <script
    src="https://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossOrigin="anonymous"
  />
</head>
Run Code Online (Sandbox Code Playgroud)

但是有一个警告:这是跨O起源,而不是跨源的。在这一点上,如果您$甚至在中使用componentDidMount,它仍然会引发错误,因为webpack不了解jquery。

添加external到Webpack配置中gatsby-node.js

我们需要通知webpack有关jQuery的信息。

// src/html.js
<head>
  <script
    src="https://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossOrigin="anonymous"
  />
</head>
Run Code Online (Sandbox Code Playgroud)

用法

现在,componentDidMount您可以

//gatsby-node.js
exports.onCreateWebpackConfig = ({
  actions,
}) => {
  const { setWebpackConfig } = actions;
  setWebpackConfig({
    externals: {
      jquery: 'jQuery', // important: 'Q' capitalized
    }
  })
}
Run Code Online (Sandbox Code Playgroud)

为什么区分大小写

设置好之后,external: { X: Y }我们实际上是在告诉webpack“无论我在哪里import X”,都应Y在全局范围内查找。在我们的案例中,webpack将在jQuery中查找window。jQuery用两个名称将自己附加到窗口:jQuery$。这就是大写Q很重要的原因。

另外,为说明起见,您也可以执行以下操作:external: { foo: jQuery }并像一样使用它import $ from foo。它仍然应该工作。

希望有帮助!