在 Gatsby/TypeScript 项目中设置导入别名

5

我尝试在我的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

2个回答

4

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

如果您想在导入时添加别名,或者使用多重相对路径以避免出现以下情况:

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

您可以通过在gatsby-node.js文件中添加setWebpackConfigAPI来轻松更改webpack配置:
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")
      }
    }
  });
}

第一个片段允许您从node_modules进行动态导入,第二个片段是您的/components文件夹。

要解决ESlint导入问题,您需要安装eslint-import-resolver-alias插件:

npm i -D eslint-import-resolver-alias

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

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

您可能会发现这篇文章很有帮助。


0

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接