简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM