使用Webpack编译.ts和.less

时间:2019-02-26 11:01:39

标签: typescript webpack less

我正在尝试使用单独的条目来编译TypeScript和Less文件。

package.json:

"devDependencies": {
    "css-loader": "^2.1.0",
    "less-loader": "^4.1.0",
    "mini-css-extract-plugin": "^0.5.0",
    "style-loader": "^0.23.1",
    "ts-loader": "^5.3.3",
    "typescript": "^3.3.3",
    "url-loader": "^1.1.2",
    "webpack": "^4.29.5",
    "webpack-cli": "^3.2.3"
  }

webpack.config.js:

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const isProduction = process.env.NODE_ENV === 'production';

module.exports = {
    entry: {
        ts: './TypeScript/index.ts',
        less: './Less/index.less'
    },
    resolve: {
        extensions: ['.ts', '.js', '.less', '.css'],
        alias: { // workaround issue with lib https://github.com/globalizejs/globalize/issues/814
            'cldr$': 'cldrjs',
            'cldr': 'cldrjs/dist/cldr'
        }
    },
    output: {
        filename: 'bundle-[name].js',
        path: path.resolve(__dirname, 'wwwroot/bundles/')
    },
    devtool: isProduction ? 'none' : 'source-map',
    module: {
        rules: [
            {
                test: /\.ts$/,
                use: [{
                    loader: 'ts-loader'
                }]
            },
            {
                test: /\.(le|c)ss$/,
                use: [{
                    loader: MiniCssExtractPlugin.loader,
                }, {
                    loader: 'css-loader'
                }, {
                    loader: 'less-loader'
                }]
            },
            {
                test: /\.(png|woff|woff2|eot|ttf|svg)$/,
                loader: 'url-loader?limit=100000'
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            // Options similar to the same options in webpackOptions.output
            // both options are optional
            filename: '[name].css',
            chunkFilename: '[id].css',

        })
    ],
};

它生成3个文件:bundle-less.js,bundle-ts.js和less.css。如何防止生成bundle-less.js?因为我只需要编译的打字稿和.css文件。还是有理由将其包含在我的网站中?我将不胜感激。

1 个答案:

答案 0 :(得分:0)

这是mini-css-extract-plugin的已知问题。您可以检查其进度和一些解决方法here

最终HTML中无需包含bundle-less.js。另外,您可以确认自己仅包含一些样板Webpack代码,因为样式已从其中提取。

可能的解决方法

  • HtmlWebpackPlugin中排除此文件(如果您正在使用它生成最终的html)
plugins: [
    //...
    new HtmlWebpackPlugin({
        template: 'template.html',
            excludeAssets: [/bundle\-less\.js/],
        }),
        new HtmlWebpackExcludeAssetsPlugin()
],
  • 构建后删除此文件
    • 简单地rm上的postbuild npm钩子上
    • 配置del-webpack-plugin (或类似文件)删除这些不需要的文件