16

我已经用 gatsby.js 试验了一段时间,除了这个问题外,一切都很顺利,我不能在应用程序中包含 jQuery 脚本,以便在渲染 gatsby 应用程序后加载,我已经包含了脚本标签文件并加载它,html.js但似乎代码是在反应将内容呈现到我尝试使用的屏幕之前执行的,simple-load-script以将其包含componentDidMount在应用程序的方法中html.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,
}

如您所见,我替换了componentDidMount()写入控制台的方法,并且没有阻止该方法执行的东西。

如果有人有这方面的经验,请分享,谢谢。

4

2 回答 2

26

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

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

将 jQuery 添加到html.js

⚠️编辑:这应该通过 来完成gatsby-ssr,请参阅@rosszember 答案以了解上下文。.

您可能已经这样做了: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>

但有一点需要注意:它是crossorigin,而不是 crossorigin。此时,如果你使用$even in componentDidMount,它仍然会抛出错误,因为 webpack 不知道 jquery。

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

我们需要通知 webpack 关于 jQuery。

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

用法

现在,componentDidMount你可以做

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

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

为什么区分大小写

当我们设置时,external: { X: Y }我们实际上是在告诉 webpack '无论我在哪里',在全局范围内import X寻找。Y在我们的例子中,webpack 会jQuerywindow. jQuery 将自身附加到具有 2 个名称的窗口:jQuery$. 这就是为什么大写的 Q 很重要。

此外,为了说明,您还可以:external: { foo: jQuery }并像import $ from foo. 它应该仍然有效。

希望有帮助!

于 2019-02-02T17:26:01.527 回答
20

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

将 jQuery 添加到 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>,
  ])
}

它会将您的脚本标签放在注释的顶部:如果您正在运行开发环境,您需要再次运行它以使 gatsby-ssr.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!")
  });
}

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

免责声明

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

此外,盖茨比指南不推荐使用 html.js:

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

于 2020-03-10T09:46:57.563 回答