Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include local javascript on a Gatsby page?

I'm a total React newbie and I guess there is something fundamental I don't quite understand here. A default Gatsby page looks like this. Is there a way to use a local .js file somewhat like this?

<script src="../script/script.js"></script>

What I would like to achieve is to have react ignore script.js but still have the client side use it. A default Gatsby page looks like this, is it possible to do somerthing like that there?

import React from "react"
import { Link } from "gatsby"

import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"

const IndexPage = () => (
  <Layout>
    <SEO title="Home" keywords={[`gatsby`, `application`, `react`]} />
    <h1>Hi people</h1>
    <p>Welcome to your new Gatsby site.</p>
    <p>Now go build something great.</p>
    <div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
      <Image />
    </div>
    <Link to="/page-2/">Go to page 2</Link>
  </Layout>
)
like image 210
Matias Heikkilä Avatar asked Feb 22 '19 20:02

Matias Heikkilä


Video Answer


1 Answers

After several hours of frustration I finally stumbled upon discussion on GitHub that solved this for me. In Gatsby, there is a thing called static folder, for which one use case is including a small script outside of the bundled code.

Anyone else in the same situation, try proceeding as follows:

  1. Create a folder static to the root of your project.

  2. Put your script script.js in the folder static.

  3. Include the script in your react dom with react-helmet.

So in the case of the code I posted in my original question, for instance:

import React from "react"
import Helmet from "react-helmet"
import { withPrefix, Link } from "gatsby"

import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"

const IndexPage = () => (
  <Layout>
    <Helmet>
        <script src={withPrefix('script.js')} type="text/javascript" />
    </Helmet>
    <SEO title="Home" keywords={[`gatsby`, `application`, `react`]} />
    <h1>Hi people</h1>
    <p>Welcome to your new Gatsby site.</p>
    <p>Now go build something great.</p>
    <div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
      <Image />
    </div>
    <Link to="/page-2/">Go to page 2</Link>
  </Layout>
)

Notice the imports

import Helmet from "react-helmet"
import { withPrefix, Link } from "gatsby"

and the script element.

<Helmet>
    <script src={withPrefix('script.js')} type="text/javascript" />
</Helmet>

This would have saved hours of my time, hopefully this does it for someone else.

like image 190
Matias Heikkilä Avatar answered Oct 08 '22 21:10

Matias Heikkilä