繁体   English   中英

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

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

我一直在尝试 gatsby.js 一段时间,除了这个问题,一切都很顺利,我无法将 jQuery 脚本包含到应用程序中,以便在 gatsby 应用程序呈现后加载,我已经包含了脚本标签html.js文件并加载它,但似乎代码是在 react 将内容呈现到屏幕之前执行的,我已经尝试使用simple-load-script并将其包含在html.js应用程序的componentDidMount方法中。 但不幸的是,这是我的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()方法以写出到控制台,并且没有阻止此方法执行的内容。

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

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

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

将 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>

但有一点需要注意:它是跨Ørigin,不crossorigin。 此时,如果您甚至在componentDidMount使用$ ,它仍然会抛出错误,因为 webpack 不知道 jquery。

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

我们需要通知 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 会在window寻找jQuery jQuery 将自身附加到具有 2 个名称的窗口: jQuery$ 这就是为什么大写的 Q 很重要。

此外,为了说明,您还可以执行以下操作: external: { foo: jQuery }并像import $ from foo一样使用它。 它应该仍然有效。

希望有帮助!

将 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>,
  ])
}

它将把你的脚本标签放在顶部注意:如果你正在运行一个开发环境,你需要再次运行它以使 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!")
  });
}

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

免责声明

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

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

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

暂无
暂无

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

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