How to include jQuery in a Gatsby.js project?

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

  • add jquery CDN to html.js
  • add external to webpack config in gatsby-node.js

Add jQuery to html.js

⚠️ Edit: This should be done via gatsby-ssr, please refer @rosszember answer for context..

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>

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.

Add external to webpack config in gatsby-node.js

We need to inform webpack about jQuery.

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

Usage

Now, in componentDidMount you can do

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

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

Hope that helps!

Leave a Comment