Search code examples
typescriptgatsbyeslint-config-airbnbtypescript-eslintparser

Set up import aliases in Gatsby / Typescript project


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


Solution

  • 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']],
        },