Webpack - Best way to update HTML to include lates

2019-07-09 05:13发布

I'm using webpack to generate hashed bundle filenames.

Assuming I'm using static HTML, CSS & JS, what is the best way to automatically update index.html to point to the latest bundles?

For example,

update:

<script src="e8e839c3a189c25de178.app.js"></script>
<script src="c353591725524074032b.vendor.js"></script>

to:

<script src="d6cba2f2e2fb3f9d98aa.app.js"></script>
<script src="c353591725524074032b.vendor.js"></script> // no change

automatically everytime a new bundle version is available.

1条回答
时光不老,我们不散
2楼-- · 2019-07-09 05:26

Amazingly, this is what the html-webpack-plugin is for.

var webpack = require('webpack');
var path = require('path');
var HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = function(env) {
    return {
        entry: {
            main: './src/index.js',
            vendor: 'moment'
        },
        output: {
            filename: '[chunkhash].[name].js',
            path: path.resolve(__dirname, 'dist')
        },
        plugins: [
            new webpack.optimize.CommonsChunkPlugin({
                names: ['vendor', 'manifest']
            }),
            new HTMLWebpackPlugin({
                tempate: path.join(__dirname, './src/index.html')
            })
        ]
    }
};

This generates an index.html in the dist directory that includes the script's in the correct order.

youtube example

查看更多
登录 后发表回答