【问题标题】:How should I access hash bundle file name in index.ejs using webpack DefinePlugin我应该如何使用 webpack DefinePlugin 访问 index.ejs 中的哈希包文件名
【发布时间】:2019-12-03 09:46:38
【问题描述】:

我想要 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 文件。

【问题讨论】:

  • 你不需要这个。将您的所有部门包含到 index.js 中,使用 webpack 编译它并作为脚本 bundle.[hash].js 包含到您的文档中。
  • 使用 HtmlWebpackPlugin?
  • 这是可能的方法之一。
  • 不,它不适用于我正在使用的 preact 配置。更清楚地说,我使用的是模板 github.com/preactjs-templates/widget 。如何输出散列的捆绑文件并在 index.ejs 中的 script.src=`bundle.[hash].js 中使用该文件名

标签: javascript reactjs webpack preact


【解决方案1】:

这个任务可以通过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 将用作default

【讨论】:

  • 请注意,引用的插件页面上显示的示例要简单得多,并且更接近常规的 webpack 使用。
  • 我猜是这样,这是 OP 使用的 preact.config.js 的扩展示例。
  • 你是对的 - 只是为寻找如何使用插件的更通用示例的人指明了方向。抱歉,如果效果不好,现在无法编辑。 :)
【解决方案2】:

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

  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`;

【讨论】:

    猜你喜欢
    • 2021-10-27
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-04
    相关资源
    最近更新 更多