Webpack 4和awesome-typescript loader无法解决别名问题

14

我目前遇到了一个问题,无法正确使用别名。据我所知,要使webpack正确使用别名,必须:

版本

  "typescript": "2.8.3",
  "webpack": "4.16.2",
  "webpack-cli": "3.1.0",
  "awesome-typescript-loader": "5.2.0",
  "html-webpack-plugin": "3.2.0",
  "source-map-loader": "^0.2.3",
  1. 将别名定义为tsconfig中的路径。 通过构建验证我的tsconfig和路径/别名是否正确。 如果没有正确配置,则会导致构建失败。

tsconfig.json

这是示例文件

Sample.tsx

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import Footer from '@common/Footer';

export default class Sample{

    public static page(): void {
        ReactDOM.render(<Footer/>,
            document.getElementById('footer')
        );
    }
}

使用webpack时,它被配置为使用awesome-typescript-loader。据我了解,它利用TsConfigPathsPlugin来检查tsconfig中的所有别名,然后进行解析。因此,在到达webpack之前,别名已经被解析。然而,实际情况并非如此。在bundle.js中,我希望不会看到任何@common或任何别名,并且它已被转换。
我还尝试在resolve中使用alias/aliasFields直接解析别名,但仍然没有成功。
webpack.js
 const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const webpack = require('webpack');
    const fs = require('fs');
    const TsConfigPathsPlugin = require('awesome-typescript-loader').TsConfigPathsPlugin;
    const ROOT_DIR = path.resolve(__dirname, ".","..");

    const config = {
        context: path.resolve(__dirname, '.',".."),
        mode: "development",
        resolve: {
            modules: [

            ],
            extensions: ['.ts', '.tsx', '.js', '.jsx'],
            plugins: [
                new TsConfigPathsPlugin({
                    configFileName: path.resolve(ROOT_DIR,'tsconfig.json')
                })
            ],
            aliasFields: ["@entry", "@common"],
            alias: {
                "@entry": "entry/",
                "@common": "common/"
            }
        },
        entry: {
            entryPoint: path.resolve(ROOT_DIR,'entry, 'index.tsx')
        },
        optimization: {
            minimize: false, // debugging purpose
            runtimeChunk: 'single',
            splitChunks: {
                cacheGroups: {
                    vendors: {
                        test: /[\\/]node_modules[\\/]/,
                        name: 'vendors',
                        chunks: 'all'
                    }
                }
            }
        },
        output: {
            filename: "[name]_bundle.js",
            path: path.join(ROOT_DIR, 'dist_w'),
        },

        // Enable sourcemaps for debugging webpack's output.
        devtool: "eval-source-map",

        resolve: {
            // Add '.ts' and '.tsx' as resolvable extensions.
            extensions: [".ts", ".tsx", ".js", ".json"]
        },

        module: {
            rules: [
                // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
                { test: /\.(ts|tsx)$/, loader: "awesome-typescript-loader" },

                // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
                { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
            ]
        },
        plugins: [
            //Generate index.html in /dist => https://github.com/ampedandwired/html-webpack-plugin
            new HtmlWebpackPlugin({
                filename: 'index.html', //Name of file in ./dist/
                template:  path.resolve(ROOT_DIR,'entry-point', 'index.html'),
                hash: true,
            })
        ],
        stats: { //object
            assets: true,
            colors: true,
            errors: true,
            errorDetails: true,
            hash: true
            // ...
        }
    };

    module.exports = config;

我收到的来自webpack的错误信息是:
Module not found: Error: Can't resolve '@common\Footer' in 'entry\src'
resolve '@common\Footer' in 'entry\src'
  Parsed request is a module
  using description file: <root>\package.json (relative path: ./entry/)
    Field 'browser' doesn't contain a valid alias configuration
    resolve as module
      entry\node_modules doesn't exist or is not a directory
      <root>\..\..\node_modules doesn't exist or is not a directory
      <root>\..\node_modules doesn't exist or is not a directory
      <root>\node_modules doesn't exist or is not a directory
      looking for modules in <root>\node_modules
        using description file: <root>\package.json (relative path: ./node_modules)
          Field 'browser' doesn't contain a valid alias configuration
      looking for modules in entry\node_modules
        using description file: <root>\package.json (relative path: ./entry-point/node_modules)
          Field 'browser' doesn't contain a valid alias configuration
          using description file: <root>\package.json (relative path: ./node_modules/@common//Footer)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
          using description file: <root>\package.json (relative path: ./entry-point/node_modules/@common/Footer)
            no extension
              Field 'browser' doesn't contain a valid alias configuration
              <root>\node_modules\@common\Footer doesn't exist
            .ts
          

任何建议都将不胜感激, 谢谢, D


你的错误信息表明它只在 node_modules 文件夹内搜索模块。resolve.modules 选项默认为 [node_modules]。如果你将 resolve.modules 选项设置为类似 [path.resolve('./')] 的内容,可能会解决这个问题。不过我对此还不确定,所以暂时不将其作为答案添加。 - Rick
我转向使用ts-loader,因为我无法将其与awesome-typescript loader正确地配合使用。 - darewreck
2个回答

9

这是我在一个项目中使用的内容,你需要在tsconfig和webpack.config中进行配置,但是这些值是不同的:

  // webpack.config
  resolve: {
    extensions: [".ts", ".js"],
    alias: { "@src": path.resolve(__dirname, "src") },
  },

  // tsconfig
  "paths": {
    "@src/*": ["./src/*"]
  },

1

对于那些寻找简单解决方案的人,请使用tsconfig-webpack-plugin。它直接从tsconfig.json中选择配置路径,并且还遵守路径别名中的splat(*)运算符。

使用tsconfig-webpack-plugin的示例webpack配置如下:

  module.exports = {
    ...
    resolve: {
      plugins: [new TsconfigPathsPlugin({/* options: see below */})]
    }
    ...
  }

请注意,与普通插件不同,这个插件应该不被注入到根目录的plugins中,而是注入到resolve.plugins选项中。
配置后,您的路径别名将按预期工作。

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