Don’t use global gatsby-cli when you start/build your gatsby apps

Don’t use global gatsby-cli when you start/build your gatsby apps

GatsbyJS provides a very neat CLI tool gatsby-cli which allows you to scaffold a new project using a template. In order to be available in your terminal you have to install it globally.

$ yarn global add gatsby-cli

It also can be used to start a development server or build the app in you current working directory. If you create a new gatsby project using the official default starter, `$ cd` into the project directory and look into the supplied package.json you will notice that it comes already with predefined scripts:

"scripts": {
  "build": "gatsby build",
  "develop": "gatsby develop",
  "format": "prettier --write src/**/*.{js,jsx}",
  "start": "npm run develop",
  "serve": "gatsby serve",
  "test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\""
},

These can be run using $ npm run or $ yarn

What is the difference when you use the globally provided $ gatsby against the locally available npm scripts?

Today I stumbled upon a strange issue when I installed the excellent `svg-sprite-loader` webpack loader by kisenka. I set it up using Gatsby APIs as usual but was getting a strange error:

Module build failed (from ./node_modules/svg-sprite-loader/lib/loader.js):
Error: Cannot find module 'webpack/package.json'

Quite unlikely that I don’t have webpack :) Turns out svg-sprite-loader is trying to figure what is the version of webpack running by using require.main which essentially is doing a require as the top-most node process. In my case I was using the gatsby-cli utils and my node resolve context was that of gatsby-cli package and not that of my current project. Also webpack is not a dependency of gatsby-cli which explains why I got that error in the first place.

This being an edge-case or not is an example of what might cause unexpected issues which may seem difficult to debug. Another reason to always use local npm tasks is the fact that in a serverless environment like Netlify we will never use global gatsby-cli to build our applications.