code, coding, vs code

Using project node_modules binaries in Terminal in VS Studio Code or Intellij (PhpStorm/WebStorm) without npx or bunx

TLDR;

If you’re using an IDE like PhpStorm or VS Code on macOS, this guide helps streamline your Node.js workflow by automatically adding the binareis in the binaries in your ‘node_modules’ directory to your terminal’s path when it starts in a relevant directory (from within the IDE). This is achieved by adding a few lines to your ~/.zprofile file.

Introduction

When working with Node.js projects in IDEs such as PhpStorm or VS Code, managing the Node.js executable path can be crucial for running scripts and commands directly from the terminal without using npx or bunx.

This guide presents a solution to automatically update the terminal’s PATH environment variable when a node_modules folder is found on execution (from within the terminal of your IDE), ensuring that Node.js commands work seamlessly.

Problem

When starting a terminal session within a project directory containing ‘node_modules’, the terminal might not recognize Node.js binary commands. This can lead to inconveniences like having to provide the full path to node binaries, using npx or bunx or not being able to execute project-specific commands.

Solution

To address this issue, we can modify the ~/.zprofile file on macOS to automatically add the ‘node_modules/.bin’ directory to the PATH when the terminal starts in a directory with ‘node_modules’. The provided code snippet accomplishes this by checking for the existence of the ‘node_modules’ directory and appending its ‘.bin’ subdirectory to the PATH.

Add the following to your ~/.zprofile file:

if [ -d "node_modules" ]; then
  export PATH="./node_modules/.bin:$PATH"
fi

Explanation

The piece of code works as follows:

  • The conditional statement [ -d "node_modules" ] checks if the ‘node_modules’ directory exists in the current working directory.
  • If the directory is found, The export PATH="./node_modules/.bin:$PATH" line appends the ‘node_modules/.bin’ directory to the beginning of the PATH variable. This ensures that locally installed Node.js binaries take precedence over globally installed ones.

Conclusion

By adding these lines to your ~/.zprofile file, you streamline your Node.js development workflow within IDEs. This enhancement facilitates the execution of Node.js commands, making it more convenient and efficient to work on Node.js projects.

Happy Coding,
Sebastiaan


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *