简体   繁体   中英

How to access webpack generated js file from index.html

I have a Flask app that is serving a template index.html , which in turn access a javascript file generated by webpack. The issue is that I am generating a hash for the webpack generated file, to prevent the browser from caching, and I cannot figure out how to access the webpack generated file, as the hash name can change. For example, if the webpack generates a file called bundle-cdcf74127a4e321fbcf0.js , I would not know the hash function cdcf74127a4e321fbcf0 ahead of time, and so I could not access it in index.html .

Here is my webpack config file:

const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
    entry: "./js/main.js",
    output: {
        filename: "static/bundle-[hash].js",
    },
    resolveLoader: {
    moduleExtensions: ['-loader']
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel',
                query: {
                    presets: ['react', 'es2015', 'stage-0']
                }
            },
            {
                test: /\.css$/,
                loader: 'style-loader',
            },
            {
                test: /\.css$/,
                loader: 'css-loader',
                query: {
                    modules: true,
                    localIdentName: '[name]__[local]___[hash:base64:5]'
                }
            }
        ]
    },
    plugins: [new CleanWebpackPlugin(['static/bundle*.js'])]
};

The code used to call the webpack generated file in index.html is below (this code does not work, as it appears that asterisk search does not work in the file name here):

<body>
    <div id="app"></div>
    <script src="bundle*.js"></script>
</body>

The flask app code goes like:

app = Flask(__name__, static_url_path='')
@app.route('/')
def default():
    return render_template('index.html')

How would I fix this code so that it serves the webpack generated file?

You need to use the webpack plugin htmlWebpackPlugin, refer to https://github.com/jantimon/html-webpack-plugin#configuration .

You can provide a html template for this plugin to inject the js files generated by webpack, pay close attention to these configuration options: template , inject , chunks , 'hash'.

new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
    template: './index.html'
    favicon: './favicon.ico',
    filename: './dist/index.html'
    inject: 'body',
    chunks: ['vendor', 'app'],
    minify: {
      collapseWhitespace: true,
      removeComments: true,
      removeAttributeQuotes: true
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM