Loading External Scripts in Gatsby Js

Gatsby Js is a great way of creating cool sites with react and it being a JavaScript based library it’s impossible to add external script files (locally or CDN) outside the ones it comes preinstalled with but as hacky as the world of programming is there has been quite number of ways to add external scripts to a Gatsby project though it’s not as easy as you’ll have to do a bit of hacking in your code but hey I’ve found an easy solution to that and that’s what I’ll be sharing today.

Steps:

1.Create your Gatsby project through the Gatsby CLI 2.Add Gatsby plugin called gatsby-plugin-load-script that helps in importing external script files using the command npm install gatsby-plugin-load-script .

Configuration of this is plugin is very confusing but it can be done easily.

Let me show you how

  1. To use scripts from a CDN, Add this line of code in the image below to your gatsby-config.js file.
    module.exports = {
    /* Your site config here */
    plugins: [`gatsby-plugin-sass`,
    {
     resolve: 'gatsby-plugin-load-script',
     options: {
       src: "https://use.fontawesome.com/f419a3889b.js",
     },
    },],
    }
    
    To add scripts locally, create a folder called static at the root of your project directory and import or create your script file in that folder.

Add the local file using the code below.

module.exports = {
  /* Your site config here */
  plugins: [`gatsby-plugin-sass`,
  {
    resolve: 'gatsby-plugin-load-script',
    options: {
      src: "/font-awesome.js",
    },
  },],
}

Note: The code gatsby-plugin-sass is another gatsby plugin i'm using in my project and it's cool if you don't see it in your gatsby-config.js file.

Bravo, At this point our script file is ready and can be used everywhere in our project. You can read more about the plugin here

Thanks for your time and please do leave a suggestions and comments in the comment section.