【问题标题】:Set up import aliases in Gatsby / Typescript project在 Gatsby / Typescript 项目中设置导入别名
【发布时间】:2021-04-09 10:02:33
【问题描述】:

我尝试在我的 Gatsby 和 Typescript 项目中创建导入别名。我使用 npm 包eslint-import-resolver-alias

所以我可以使用:

import Layout from '@components/Layout';

gatsby-node.js 我有:

const path = require('path');

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

.eslintrc.js 我有:

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

我有:

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

现在我在 VSCode 中收到此错误:

无法解析模块路径 'components/layout'.eslintimport/no-unresolved

【问题讨论】:

    标签: typescript gatsby eslint-config-airbnb typescript-eslintparser


    【解决方案1】:

    我通过在.eslintrc.js 中添加paths: ['./src'],import/resolver 使其工作:

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

    【讨论】:

      【解决方案2】:

      您不需要gatsby-plugin-resolve-src 来允许从/src 导入。默认情况下,它由 Gatsby 处理。如果正确导出,项目文件夹中的所有内容都可以作为 React 组件导入。

      如果你想在你的导入中添加别名,路径的多重相对性以避免类似的事情:

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

      您可以通过添加setWebpackConfig API(在您的gatsby-node.js 中:

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

      另外,您可以添加:

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

      第一个 sn-p 将允许您从 node_modules 动态导入,第二个在您的 /components 文件夹中。

      要解决 ESlint 导入问题,需要通过以下方式安装 eslint-import-resolver-alias 插件:

      npm i -D eslint-import-resolver-alias
      

      然后在你的.eslint文件中添加如下配置:

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

      您可能会发现this article 很有帮助。

      【讨论】:

        猜你喜欢
        • 2022-10-22
        • 2016-11-30
        • 1970-01-01
        • 2013-10-07
        • 1970-01-01
        • 1970-01-01
        • 2015-10-15
        • 2018-12-23
        • 2021-06-10
        相关资源
        最近更新 更多