【问题标题】:Aliasing with Webpack 4 and awesome-typescript loader not workingWebpack 4 的别名和 awesome-typescript 加载器不起作用
【发布时间】:2019-01-08 11:38:11
【问题描述】:

我目前在让别名正常工作时遇到问题。据我了解,要让别名与 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 和路径/别名是正确的。如果配置不正确,构建将失败。

这里是示例文件

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 或任何别名,并且它会被转换。

我还添加了尝试直接在 webpack 中解析别名以及解析中的 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('./')] 之类的值,您可能会解决问题。不过不确定这一点,所以暂时不要添加这个作为答案。
  • 我搬到 ts-loader 因为我无法让它与 awesome-typescript 加载器一起正常工作

标签: typescript webpack webpack-4 type-alias


【解决方案1】:

这是我在我的一个项目中使用的,您必须在 tsconfig 和 webpack.config 中配置它,但值不同:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    请注意,与普通插件不同,这不应注入到 root plugins,而是注入到 resolve.plugins 选项中。

    发布此配置,您的路径别名将按预期工作?

    【讨论】:

      猜你喜欢
      • 2018-12-07
      • 2018-01-31
      • 1970-01-01
      • 2016-11-03
      • 2017-09-02
      • 2018-06-25
      • 2018-09-12
      • 1970-01-01
      • 2018-04-22
      相关资源
      最近更新 更多