如何在Gatsby.js项目中包含jQuery? [英] How to include jQuery in a Gatsby.js project?

查看:103
本文介绍了如何在Gatsby.js项目中包含jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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. But with no luck, here is the source code to my html.js file:

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()方法以写入控制台,但并没有阻止该方法执行的内容.

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.

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

If anyone has experience with this please do share, thanks.

推荐答案

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

If you want to add jQuery as an external (load from CDN) to gastby, it's a bit tricky. You'd need to:

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

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

You've probably already done this: cp .cache/default-html.js src/html.js, and add

// src/html.js
<head>
  <script
    src="https://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossOrigin="anonymous"
  />
</head>

但是有一个警告:它是交叉的 O 绑定,而不是跨源的. 此时,即使您在componentDidMount中也使用$,它仍然会引发错误,因为webpack不了解jquery.

But there's a caveat: it's crossOrigin, not crossorigin. At this point, if you use $ even in componentDidMount, it'd still throw error, as webpack doesn't know about jquery.

我们需要将有关jQuery的信息告知webpack.

We need to inform webpack about 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将自己附加到具有两个名称的窗口:jQuery$.这就是大写Q很重要的原因.

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. In our case, webpack'll look for jQuery in window. jQuery attachs itself to window with 2 names: jQuery and $. This is why the capitalized Q is important.

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

Also, to illustrate, you can also do: external: { foo: jQuery } and use it like import $ from foo. It should still work.

希望有帮助!

这篇关于如何在Gatsby.js项目中包含jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆