Set up import aliases in Gatsby / Typescript project

2.9k Views Asked by At

I try to create import aliases in my Gatsby and Typescript project. I use npm package eslint-import-resolver-alias.

So I am able to use:

import Layout from '@components/Layout';

In gatsby-node.js I have:

const path = require('path');

exports.onCreateWebpackConfig = ({ actions }) => {
  actions.setWebpackConfig({
    resolve: {
      alias: {
        @components: path.resolve(__dirname, 'src/components'),
        @static: path.resolve(__dirname, 'static'),
      },
    },
  });
};

In .eslintrc.js I have:

alias: [['@components', './src/components']]

In I have:

"baseUrl": "./src",
    "paths": {
      "@components": ["/components"]

Now I get this error in VSCode:

Unable to resolve path to module 'components/layout'.eslintimport/no-unresolved

2

There are 2 best solutions below

0
On BEST ANSWER

I got it working by adding paths: ['./src'], to import/resolver inside .eslintrc.js:

'import/resolver': {
      node: {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
        paths: ['./src'],
      },
      alias: [['components', './src/components']],
    },
0
On

You don't need gatsby-plugin-resolve-src to allow imports from /src. By default, it's handled by Gatsby. Everything that it's inside the project's folder it's importable as a React component if it's properly exported.

If you want to add aliasing in your imports, multiple relativity of the paths in order to avoid something like:

import Subscribe from '../../../../../../../core/modules/newsletter/mixins/Subscribe'

You can simply change your webpack's configuration by adding setWebpackConfig API (in your gatsby-node.js:

exports.onCreateWebpackConfig = ({ actions }) => {
  actions.setWebpackConfig({
    resolve: {
      modules: [path.resolve(__dirname, `src`), `node_modules`],
    },
  });
};

Additionally, you can add:

const path = require("path");
exports.onCreateWebpackConfig = ({ actions }) => {
  actions.setWebpackConfig({
    resolve: {
      alias: {
        "@components": path.resolve(__dirname, "src/components"),
        "@static": path.resolve(__dirname, "static")
      }
    }
  });
}

The first snippet will allow you to make dynamic imports from node_modules and the second one in your /components folder.

To resolve the ESlint import, you need to install eslint-import-resolver-alias plugin by:

npm i -D eslint-import-resolver-alias

And then add the following configuration in your .eslint file:

{
  "settings": {
    "import/resolver": {
      "alias": [
        ["@components", "./src/components"]
      ]
    }
  }
}

You may find this article helpful.