简体   繁体   中英

How should I access hash bundle file name in index.ejs using webpack DefinePlugin

I want hashed bundle file name in preact project. in preact.config.js the output file is as config.output.filename = "[name].[hash].js";

Plugin is defined using webpack.DefinePlugin() as shown below:

config.plugins.push(
    new DefinePlugin({
      process: {
        env: {
          API_URL: JSON.stringify(process.env.API_URL),
          FILE_NAME: JSON.stringify(config.output.filename)
        }
      }
    })
  );

Is there any way to include the bundle.[hash].js file in index.ejs.

This task can be solved via HtmlWebpackPlugin , all the options can be controlled through options :

export default (config, env, helpers) => {
    delete config.entry.polyfills;

    // add hash to the file name.
    config.output.filename = "[name].[hash].js";

    let {plugin} = helpers.getPluginsByName(config, "ExtractTextPlugin")[0];

    let html_webpack = helpers.getPluginsByName(config, 'HtmlWebpackPlugin')[0];

    // not sure why but without this option it does not inject script tag.
    html_webpack.plugin.options.hash = true;

    plugin.options.disable = true;

    if (env.production) {
        config.output.libraryTarget = "umd";
    }
};

In this case, the template index.ejs will be used as default .

I tried to solve this problem by creating a hash function by myself and exporting the hash function.

  const hashNumber = hashGenerator();
  delete config.entry.polyfills;
  config.entry.app = "./index.js"
  config.output.filename = "[name]."+hashNumber+".js";

  let { plugin } = helpers.getPluginsByName(config, "ExtractTextPlugin")[0];
  plugin.options.disable = true;

  if (env.production) {
    config.output.libraryTarget = "umd";
  }

  config.plugins.push(
    new DefinePlugin({
      process: {
        env: {
          HASH: JSON.stringify(hashNumber)
        }
      }
    })
  );
};

and including that hash in index.ejs file

script.src = `/bundle.<%= process.env.HASH %>.js`;

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