Menu

Run Gulp as You Open a VS Code Project

October 12th, 2020

When I open my local project for this very site, there is a 100% chance that I need to run this command before anything else: gulp. I set that up fresh less than a year ago so I’m on the latest-and-greatest stuff and have my workflow just how I like it. I did a few more tweaks a few months later to make things a smidge nicer (even adding a fancy fun little dock icon!).

That’s when I learned about VS Code Tasks. Generically, the can just run command-line tasks that you configure whenever you choose to run them by name. But I’m particularly compelled by the idea that they can run when you open a project.

It’s this easy to run Gulp:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Run Gulp",
      "command": "gulp",
      "type": "shell",
      "runOptions": {
        "runOn": "folderOpen"
      }
    }
  ]
}

Except… that started to fail on my machine. I use nvm to manage Node versions, and despite my best effort to nvm alias default to the the correct version of Node that works nicely with Gulp, the Node version was always wrong, and thus running gulp would fail. The trick is to run nvm use first (which sets the correct version from my .nvmrc file), then gulp runs fine.

That works fine in a fresh terminal window, but for some reason, even making the command run two tasks like this (chaining them with a semicolon):

"command": "nvm use; gulp",

…it would still fail. It didn’t know what nvm meant. I don’t know what the heart of the problem is exactly (why one terminal doesn’t know the same things that another terminal does), but I did manage to sort out that the global nvm has a shell script with one job: defining the nvm command. So you “source” that, as they say, and then the nvm command works.

So my final setup is:

{
  "version": "2.0.0",
  "tasks": [
    {
      "label": "Run Gulp",
      "command": ". ~/.nvm/nvm.sh; nvm use; gulp",
      "type": "shell",
      "runOptions": {
        "runOn": "folderOpen"
      }
    }
  ]
}

And that, dear readers, runs Gulp perfectly when I open my CSS-Tricks project, which is exactly what I wanted.

High five to Jen Luker who went on this journey with me and helped me get it to the finish line. 🤚

The original post Run Gulp as You Open a VS Code Project.