Path Hacks for JavaScript Developers in VS Code

If you are a JavaScript developer, you might be used to file imports that look like this:

import { formatDate } from "../../../utils/dates";
import metadata from "../../../config/metadata.js";

With long relative imports into different folders from where you need them.

With VS Code, you can add a configuration to your JavaScript projects that can create helpful path mappings that will make these long relative imports disappear. 🪄✨

How to

In the root of your project, you'll need to create a new file named jsconfig.json.

In this file, create your aliases.

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@utils/*": ["./utils/*"],
      "@config/*": ["./config/*"]
    }
  }
}

You will need to declare the baseUrl location for this to work. It informs what directory the paths start from.

In the paths option, you can select whatever alias or keyword you want to use instead of the given path. I usually follow the naming convention with @folder/ so it's clear when I'm using the imports that it's a special import.

Now, we can rewrite our original imports like this:

// Before 🥱
import { formatDate } from "../../../utils/dates";
import metadata from "../../../config/metadata.js";

// After 🎉 No more crazy import paths!
import { formatDate } from "@utils/dates";
import metadata from "@config/metadata.js";

Notes

This file hosts some extra features enabled by VS Code's JavaScript Language Service.

If you want to read and learn more about what you can do with this file, read the docs here.

Happy coding! 💅

ProductivityVscode
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.