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

问题描述

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

解决方法

您不需要 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")
      }
    }
  });
}

第一个片段将允许您从 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 很有帮助。

,

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...