首页 > 解决方案 > 我应该如何使用 webpack DefinePlugin 访问 index.ejs 中的哈希包文件名

问题描述

我想要 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)
        }
      }
    })
  );

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

标签: javascriptreactjswebpackpreact

解决方案


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


推荐阅读