How to add custom local JS files in Gatsby correctly

Viewed 51

I´m a newbie on react and gatsby but i´m working on a little project as practice anda I have a little problem. I want to add a custom JS file to the project (little functions for a calculator on the index). I used Helmet to import them and on develop enviroment is working fine, but once build, is not.

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

export default function homePage() {
  return (
    <main>
      <Helmet>
        <script src={withPrefix('/functions.js')} type="text/javascript" />
        <script src={withPrefix('/escritura.js')} type="text/javascript" />
      </Helmet>
}

I´m not sure what I am doing wrong. Someone can help me, please? You can see the project proof version live here:

https://modest-hoover-aac2d1.netlify.app/

In the final version, every input should be filled automatically, but is not happening.

1 Answers

withPrefix is a helper function that only works in build mode because in development mode paths don't need to be prefixed:

For pathnames you construct manually, there’s a helper function, withPrefix that prepends your path prefix in production (but doesn’t during development where paths don’t need to be prefixed).

So if your code works well under development mode, just remove withPrefix and leave your code as:

export default function homePage() {
  return (
    <main>
      <Helmet>
        <script src={`/functions.js`} type="text/javascript" />
        <script src={`/escritura.js`} type="text/javascript" />
      </Helmet>
}
Related