简体   繁体   English

如果我在 tsconfig 中使用自定义路径,Webpack 开发服务器无法找到带有 Typescript 的模块

[英]Webpack Dev Server cannot find modules with Typescript if I use custom paths in tsconfig

I'm building a project from scratch on React + TypeScript and using the Webpack Dev server.我正在 React + TypeScript 上从头开始构建一个项目,并使用 Webpack 开发服务器。 I want to use relative paths to components, which will be not strict for a more flexible development.我想使用组件的相对路径,这对于更灵活的开发来说并不严格。

In my App.tsx, I'm trying to import component:在我的 App.tsx 中,我正在尝试导入组件:

import EntityTypes from "components/EntityTypes/EntityTypes";

and getting an error并得到一个错误

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

File by this path exists (/src/components/EntityTypes/EntityTypes.js) and exports the class like此路径的文件存在(/src/components/EntityTypes/EntityTypes.js)并导出 class 等

export default EntityTypes;

My tsconfig.json:我的 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: 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'
        })
    ]
};

I've checked the documentation of typescript about "paths", the file is exists, I don't understand what the problem.我检查了 typescript 关于“路径”的文档,该文件存在,我不明白是什么问题。

You're using absolute imports, not relative ones.您使用的是绝对进口,而不是相对进口。 Try import EntityTypes from "./components/EntityTypes/EntityTypes";尝试import EntityTypes from "./components/EntityTypes/EntityTypes"; , assuming the file you're importing it into is on the same level as the components directory. ,假设您要导入它的文件与components目录处于同一级别。

I have sorted out how to use paths for my files and make them flexible, that I can reorganize the project and manage paths easy without a lot of changes of strict relative paths.我已经整理了如何为我的文件使用路径并使它们变得灵活,我可以轻松地重新组织项目和管理路径,而无需对严格的相对路径进行大量更改。

The problem was related to configuration of the webpack.该问题与 webpack 的配置有关。 Final configuration is next:接下来是最终配置:

tsconfig.json tsconfig.json

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

webpack.config.js 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'),
    }
  },
}

Examples of usage使用示例

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM