首页 > 解决方案 > 如果我在 tsconfig 中使用自定义路径,Webpack 开发服务器找不到带有 Typescript 的模块

问题描述

我正在 React + TypeScript 上从头开始构建一个项目,并使用 Webpack Dev 服务器。我想使用组件的相对路径,这对于更灵活的开发来说并不严格。

在我的 App.tsx 中,我正在尝试导入组件:

import EntityTypes from "components/EntityTypes/EntityTypes";

并得到一个错误

Module not found: Error: Can't resolve 'components/EntityTypes/EntityTypes' in '/home/eugene/prj/work/crud-react/src'

此路径的文件存在(/src/components/EntityTypes/EntityTypes.js)并导出类

export default EntityTypes;

我的 tsconfig.json:

{
  "compilerOptions": {
    "sourceMap": true,
    "noImplicitAny": false,
    "module": "commonjs",
    "target": "es5",
    "lib": [
      "es2015",
      "es2017",
      "dom"
    ],
    "removeComments": true,
    "allowSyntheticDefaultImports": false,
    "jsx": "react",
    "allowJs": true,
    "baseUrl": ".",
    "paths": {
      "components/*": [
        "src/components/*"
      ]
    }
  }
}

webpack.config.js:

const HtmlWebPackPlugin = require( 'html-webpack-plugin' );
const path = require( 'path' );
module.exports = {
    context: __dirname,
    entry: './src/index.js',
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.jsx']
    },
    output: {
        path: path.resolve( __dirname, 'dist' ),
        filename: 'main.js',
        publicPath: '/',
    },
    devServer: {
        historyApiFallback: true
    },
    module: {
        rules: [
            {
                test: /\.(tsx|ts)?$/,
                loader: 'awesome-typescript-loader'
            },
            {
                test: /\.js$/,
                use: 'babel-loader',
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(png|j?g|svg|gif)?$/,
                use: 'file-loader'
            }
        ]
    },
    plugins: [
        new HtmlWebPackPlugin({
            template: path.resolve( __dirname, 'public/index.html' ),
            filename: 'index.html'
        })
    ]
};

我检查了关于“路径”的打字稿文档,该文件存在,我不明白是什么问题。

标签: reactjstypescriptwebpack

解决方案


我已经整理了如何为我的文件使用路径并使它们灵活,我可以轻松地重新组织项目和管理路径,而无需对严格的相对路径进行大量更改。

该问题与 webpack 的配置有关。接下来是最终配置:

tsconfig.json

{
  "compilerOptions": {
    // ...
    "paths": {
      "~/components/*": [
        "./src/components/*"
      ],
      "~/services/*": [
        "./src/services/*"
      ],
      "~/interfaces/*": [
        "./src/interfaces/*"
      ]
    },
  }
}

webpack.config.js

const path = require('path');
module.exports = {
  // ...
  resolve: {
    // ...
    alias: {
      '~/components': path.resolve(process.cwd(), './src/components'),
      '~/interfaces': path.resolve(process.cwd(), './src/interfaces'),
      '~/services': path.resolve(process.cwd(), './src/services'),
    }
  },
}

使用示例

import {IEntities} from "~/interfaces/entities.interface";
// ...
import EntityForm from "~/components/EntityForm/EntityForm";

推荐阅读