簡體   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