How to work with absolute path import in Gatsby

A few days ago while working on a gatsby project I found it slightly complicated to set up absolute path work.

I like the ~/ tilde absolute path import for all my files.

Here’s an example

~/components/Component
vs.
../../../../components/Component

Let’s see how I made it work.

Adding a Custom webpack Config

Gatsby has a few plugins that can help with that but I don’t like to add another package just for that plus those plugin does not work well with VS code Go to Definition. You can add your custom webpack config in your gatsby-node.js file. You can learn more about it in the official doc.

exports.onCreateWebpackConfig = ({ actions }) => {
  actions.setWebpackConfig({
    resolve: {
      alias: {
        "~": path.resolve(__dirname, "src/"),
      },
      extensions: [".ts", ".tsx", ".js", ".jsx"],
    },
  })
}

At this point, You can import your files like below.

~/components/Component
~/components/layout/Header

But you will see that in VS codes Go to Definition do not work. When you hit ctrl + left click on your react components or function that imported from another file and it does not take you to that file.

VS codes Go to Definition do not work
VS codes Go to Definition do not work

Adding a tsconfig.json or jsconfig.json file

 {
    "compilerOptions": {
      "baseUrl": "./",
      "paths": {
        "~/*": ["src/*"]
      }
    },

 }

Now you can see when you hit ctrl + left click on your react components or function it takes you to that file.

VS codes Go to Definition working now

 ? Feel free to reach out to me if you have any questions.

Dipankar Maikap

Dipankar Maikap

I'm a freelance web developer. I work out of Kolkata, India. My favorite number is 77.

Leave a Reply