使用Webpack 4和Awesome-Typescript加载程序的别名不起作用

时间:2018-08-01 01:25:57

标签: typescript webpack webpack-4 type-alias

我目前在获取别名以正常工作方面遇到问题。据我了解,要使别名能够与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或任何别名,并且它们会被转换。

我还添加了尝试直接在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;

我从Web Pack中收到的错误消息是:

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

2 个答案:

答案 0 :(得分:2)

这是我在一个项目中使用的内容,您必须在tsconfig和webpack.config中都对其进行配置,但是值是不同的:

plt.plot(mon_data.index,mond_data.groupby('Hour')['Availability'].mean())

答案 1 :(得分:0)

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

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

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

请注意,与普通插件不同,不应将其注入到根plugins中,而应注入到resolve.plugins选项中。

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

相关问题