简体   繁体   English

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

[英]How to include jQuery in a Gatsby.js project?

I've been experimenting with gatsby.js for a while and everything is going well except for this issue, i cannot include jQuery scripts unto the app so that it loads after the gatsby app has been rendered, i've the included script tags unto the html.js file and loaded it but it seems that the code is executed before react renders the content unto the screen i've tried using simple-load-script as well to include it on the componentDidMount method on the html.js app.我一直在尝试 gatsby.js 一段时间,除了这个问题,一切都很顺利,我无法将 jQuery 脚本包含到应用程序中,以便在 gatsby 应用程序呈现后加载,我已经包含了脚本标签html.js文件并加载它,但似乎代码是在 react 将内容呈现到屏幕之前执行的,我已经尝试使用simple-load-script并将其包含在html.js应用程序的componentDidMount方法中。 But with no luck, here is the source code to my html.js file:但不幸的是,这是我的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,
}

As you can see i replaced the componentDidMount() method to write out to the console and it didn't there's something preventing this method from executing.如您所见,我替换了componentDidMount()方法以写出到控制台,并且没有阻止此方法执行的内容。

If anyone has experience with this please do share, thanks.如果有人有这方面的经验,请分享,谢谢。

If you want to add jQuery as an external (load from CDN) to gastby, it's a bit tricky.如果要将 jQuery 作为外部(从 CDN 加载)添加到 gastby,则有点棘手。 You'd need to:你需要:

  • add jquery CDN to html.js将 jquery CDN 添加到html.js
  • add external to webpack config in gatsby-node.jsgatsby-node.js中将external添加到 webpack 配置

Add jQuery to html.js将 jQuery 添加到html.js

⚠️ Edit : This should be done via gatsby-ssr , please refer @rosszember answer for context. ⚠️编辑:这应该通过gatsby-ssr ,请参阅@rosszember 的答案以了解上下文。 . .

You've probably already done this: cp .cache/default-html.js src/html.js , and add您可能已经这样做了: 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>

But there's a caveat: it's cross O rigin, not crossorigin.但有一点需要注意:它是跨Ørigin,不crossorigin。 At this point, if you use $ even in componentDidMount , it'd still throw error, as webpack doesn't know about jquery.此时,如果您甚至在componentDidMount使用$ ,它仍然会抛出错误,因为 webpack 不知道 jquery。

Add external to webpack config in gatsby-node.jsgatsby-node.js external添加到 webpack 配置

We need to inform webpack about jQuery.我们需要通知 webpack 关于 jQuery。

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

Usage用法

Now, in componentDidMount you can do现在,在componentDidMount你可以做

import $ from 'jquery' // important: case sensitive.

componentDidMount() {
  $('h1').css('color', 'red');
}

Why case sensitive为什么区分大小写

When we set external: { X: Y } We're essentially telling webpack that 'wherever I do import X ', look for the Y in the global scope.当我们设置external: { X: Y }我们实际上是在告诉 webpack '无论我在哪里import X ',在全局范围内查找Y In our case, webpack'll look for jQuery in window .在我们的例子中,webpack 会在window寻找jQuery jQuery attachs itself to window with 2 names: jQuery and $ . jQuery 将自身附加到具有 2 个名称的窗口: jQuery$ This is why the capitalized Q is important.这就是为什么大写的 Q 很重要。

Also, to illustrate, you can also do: external: { foo: jQuery } and use it like import $ from foo .此外,为了说明,您还可以执行以下操作: external: { foo: jQuery }并像import $ from foo一样使用它。 It should still work.它应该仍然有效。

Hope that helps!希望有帮助!

Another way to add jQuery to your Gatsby project - using gatsby-ssr.js and gatsby-browser.js:将 jQuery 添加到 Gatsby 项目的另一种方法 - 使用 gatsby-ssr.js 和 gatsby-browser.js:

Add jQuery to gatsby-ssr.js将 jQuery 添加到 gatsby-ssr.js

You need to create a gatsby-ssr.js to your root if you didn't have one already.如果您还没有 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>,
  ])
}

It will put your script tag to the top of the Note: If you're running a development environment you need to run it again to make gatsby-ssr.js work它将把你的脚本标签放在顶部注意:如果你正在运行一个开发环境,你需要再次运行它以使 gatsby-ssr.js 工作

Add your code to gatsby-browser.js将您的代码添加到 gatsby-browser.js

You need to create a gatsby-browser.js to your root if you didn't have one already.如果您还没有 gatsby-browser.js,则需要在根目录中创建一个 gatsby-browser.js。 This will be the place for your codes:这将是您的代码的地方:

const $ = require("jquery")

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

This method puts your code into the common.js You can use other APIs as well to run your code: Gatsby Browser API doc此方法将您的代码放入 common.js 您也可以使用其他 API 来运行您的代码: Gatsby Browser API doc

Disclaimer免责声明

It's a little bit hacky and in general, it is not really recommended to use jQuery with Gatsby but for quick fixes, it works just fine.它有点老套,一般来说,真的不建议将 jQuery 与 Gatsby 一起使用,但为了快速修复,它工作得很好。

Moreover, html.js is not recommended by the Gatsby guides:此外,Gatsby 指南不推荐 html.js:

Customizing html.js is a workaround solution for when the use of the appropriate APIs is not available in gatsby-ssr.js.当 gatsby-ssr.js 中无法使用适当的 API 时,自定义 html.js 是一种变通解决方案。 Consider using onRenderBody or onPreRenderHTML instead of the method above.考虑使用 onRenderBody 或 onPreRenderHTML 代替上述方法。 As a further consideration, customizing html.js is not supported within a Gatsby Theme.作为进一步的考虑,在 Gatsby 主题中不支持自定义 html.js。 Use the API methods mentioned instead.请改用提到的 API 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM