跟我一起学习webpack输出动态HTML(三)

跟着之前的项目来

我们没打包一次就会生成一个bundile.js,我们要更新最新的代码不希望有缓存,那么这个时候我们就是更改资源的URL,
每当代码发生变化时,相应的hash也会发生变化。这个时候我们就会使用chunkhash来作为文件版本号,因为它会为每一个chunk单独计算一个hash
我们修改webpack.config.js为

运行项目,我们会发现生成随机的版本号

如果bundle.js改变的话,那我们在html中引用的是bundle.js文件名也会改变,这个时候使用html-webpack-plugin进行动态生成index.html
安装html-webpack-plugin插件


删除index.html,修改webpack.config.js文件

const path = require('path');
const htmlPlugin = require('html-webpack-plugin');
module.exports = {
    entry:'./src/index.js',
    output:{
        filename:'bundle@[chunkhash].js'
    },
    mode:'development',
    plugin:[new htmlPlugin({title:path.basename(_dirname)})],
    devServer:{
        publicPath:'/dist',
        port:'4000'
    },
};

这个时候项目的目录为

修改package.json的入口运行命令为

接着运行npm run dev
我们会发现浏览器自动打开了4000端口运行

原文地址:https://www.cnblogs.com/smart-girl/p/11334823.html