路径的别名在带有reactjs的打字稿中不起作用

问题描述 投票:0回答:1

我有一个带有打字稿的reactjs应用程序。我正在尝试使别名发挥作用。这是我的 tsconfig.json 代码

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "baseUrl": "./",
    "paths": {
      "@/src/*": ["./src/*"],
      "@/types/*": ["./types/*"],
      "@/assets/*": ["./assets/*"]
    }
  },
  "include": ["src"]
}

我的webpack配置如下

// eslint-disable-next-line @typescript-eslint/no-var-requires
const path = require('path');

module.exports = {
  test: /\.svg$/,
  use: ['@svgr/webpack'],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@assets': path.resolve(__dirname, 'assets'),
      '@types': path.resolve(__dirname, 'types'),
    },
  },
};

当我在本地主机上运行应用程序时出现此错误

ERROR in ./src/presentation/login/index.tsx 4:0-49
Module not found: Error: Can't resolve '@/src/components/screen' in 'xxxxx/src/presentation/login'

控制台中没有错误,当我单击 @/src/components/screen 时,它确实需要我更正文件,因此它仅在本地主机中。

我该如何解决这个问题

reactjs typescript webpack
1个回答
0
投票

您附加的配置文件看起来像是 SVG 模块的规则,而不是完整的配置。

我想您不小心将别名添加为 SVG 加载器规则的一部分,而不是将它们放在配置的根目录下。

而不是这个:

module.exports = {
  ...
  module: {
    rules: [
      {
        test: /\.svg$/,
        use: ['@svgr/webpack'],
        resolve: {
          alias: {
            '@': path.resolve(__dirname, 'src'),
            '@assets': path.resolve(__dirname, 'assets'),
            '@types': path.resolve(__dirname, 'types'),
          },
        },
      }
    ]
  }
}

你应该有这样的东西:

module.exports = {
  ...
  module: {
    rules: [
      {
        test: /\.svg$/,
        use: ['@svgr/webpack'],
      }
    ]
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@assets': path.resolve(__dirname, 'assets'),
      '@types': path.resolve(__dirname, 'types'),
    },
  },
}

Webpack 文档链接:

© www.soinside.com 2019 - 2024. All rights reserved.