繁体   English   中英

我应该如何使用 webpack DefinePlugin 访问 index.ejs 中的哈希包文件名

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

我想在 preact 项目中散列包文件名。 在 preact.config.js 中,输出文件为config.output.filename = "[name].[hash].js";

插件是使用webpack.DefinePlugin()定义的,如下所示:

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

有没有办法在 index.ejs 中包含bundle.[hash].js文件。

这个任务可以通过HtmlWebpackPlugin解决,所有的选项都可以通过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";
    }
};

在这种情况下,模板index.ejs将用作默认值

我试图通过自己创建一个哈希函数并导出哈希函数来解决这个问题。

  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)
        }
      }
    })
  );
};

并将该哈希包含在 index.ejs 文件中

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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