0

当我require('./something.html')在我的代码中执行并配置文件加载器以加载 html 文件时,如下所示:

...
module: {
    rules: [
        {test: /\.html$/, loader: 'file-loader', options: {name: '[name].[hash].html'}
    },
}
...

目前这会将原始文件复制到配置的输出目录并替换require对这些文件名的调用替换为生成的文件 url。效果很好。

我想知道是否有可能以某种方式进一步处理文件,例如使用任何其他加载器进一步缩小或优化。或者也许使用任何钩子或类似方法以某种方式处理它们以进行优化。不知道webpack提供那种钩子。

有什么解决方法可以做到这一点file-loader吗?

我尝试过这样的事情,但它似乎不起作用。它不是缩小的。

{
    test: /\.html$/, use: [
        {loader: 'raw-loader'},
        {loader: 'html-minify-loader'},
        {loader: 'file-loader'}
    ]
}

让我知道是否有人使用 webpack 2 对此有任何解决方法。谢谢。

注意: 我知道有html-webpack-plugin用于生成index.html这不是我想要的。我在 Angular js 1.x 项目中工作,我需要file-loader在其中使用许多模板 html 文件templateUrl来动态加载它们,这些文件已经很好用了。现在我只需要缩小那些输出模板文件。

4

1 回答 1

0

I couldn't find any way or plugin to do this job so, I created a custom webpack plugin and it did work perfectly in my case.

If anyone of you run into similar situation you may want to use this plugin too webpack-file-preprocessor-plugin

This is a very lightweight webpack plugin that allows you to pre-process files or assets loaded using file-loader before they're finally emitted.

As this is a very generic plugin you can use it to do any kind of custom pre-processing to assets just before they're finally emitted by webpack.

This example demonstrates how you can use this plugin to minify the html assets loaded using file-loader.

const webpack = require('webpack');
const WebpackFilePreprocessorPlugin = require('webpack-file-preprocessor-plugin');
const minifyHtml = require('html-minifier').minify;

module.exports = {
    entry: {
        app: './index.js'
    },
    output: {
        path: './public/dist',
        publicPath: '/dist/',
        filename: '[name].bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.html$/,
                use: {
                    loader: 'file-loader', 
                    options: {
                        name: 'tmpl/[hash].html'
                    }
                }
            }
        ]
    },
    plugins: [
        new WebpackFilePreprocessorPlugin({
            // Prints processed assets if set to true (default: false)
            debug: true,
            // RegExp pattern to filter assets for pre-processing.
            pattern: /\.html$/,
            // Do your processing in this process function.
            process: (source) => minifyHtml(source.toString())
        })
    ]
};

Check this webpack-file-preprocessor-plugin for more information.

于 2017-03-22T06:44:53.033 回答