首页 > webpack加hash打包后html中引用的bundle.js如何同时修改为对应的文件bundler.[hash].js?

webpack加hash打包后html中引用的bundle.js如何同时修改为对应的文件bundler.[hash].js?

我现在有一个index.html。里面引用了webpack打包之后的js文件。如图:

<script src="dest/bundle.js"></script>

现在我使用webpack.config.js打包。配置如下:

如上图,配置里的filname后面加了hash。每次entry.js改变之后,再次执行webpack.congif.js生成的bundle.js的文件名都不一样。

问题:如何让bundle.[hash].js改变后,index.html中引用的那个dest/bundle.js同时也改变为对应的那个文件名?

由于本人刚开始看webpack,文档都看了,网上的也查了,还是没有找到解决方案。所以来这里问问大家。


当webpack编译完成的时候会触发 done` 事件,事件的回调函数有一个参数 stats, stats可以访问到当前编译的 hash。根据这些我们可以在webpack的配置文件中的 plugins 配置项写入。另外我们需要修改html文件中的script标签内容,为了方便使用 cheerio

// webpack.config.babel.js
import webpack from 'webpack';
import cheerio from 'cheerio';
import fs from 'fs';

module.exports = {
    ... // 其他配置
    plugins: [
        // 其他插件
        function(){
            this.plugin('done', stats => {
                fs.readFile('./index.html', (err, data) => {
                    const $ = cheerio.load(data.toString());
                    $('script[src*=dest]').attr('src', 'dest/bundle.'+stats.hash+'.js');
                    fs.write('./index.html', $.html(), err => {
                        !err && console.log('Set has success: '+stats.hash)
                    })
                })
            })
        }
    ]
}

用html-webpack-plugin吧。或者自己写一个处理器


可以用 assets-webpack-plugin 插件,将资源路径输出到文件,然后后端去引用解析这个文件。

var AssetsPlugin = require('assets-webpack-plugin');

plugins: [
      new AssetsPlugin({
        filename: 'path/to/stats.json'
      })
]
// 得到 类似酱紫的 stats.json
{"index":{"js":"/pages/dashboard/index.afyao7as7f6a9sdf97a.js"}}

后端 controller 中 require('path/to/stats.json'), render 到 view 中

【热门文章】
【热门文章】