如何访问在复制 webpack 插件期间散列的静态资源的实际 name/path/url

How to access the actual name/path/url of a static resource hashed during copy webpack plugin

所以我有使用 copy webpack 插件散列的资源。

{
            from: "data/json/*.json",
            to: "data/json/[name].[hash:6].json",
},

现在,在运行时,我需要访问这些 json 文件的实际 url。 我最理想的是能够在运行时获取这个 url 这样我就可以做类似

的事情
let name = "tiles";
const tileDataUrl = requireUrl(`data/json/${name}.json`);
fetch(tileDataUrl) // tileData Url here would  data/json/tiles.abc34f.json


...

我需要的是一种方法 requireUrl(或任何它可能被调用的名称),它 returns 实际 url 静态资源在运行时具有散列。

(对于任何想知道的人,这里使用哈希来进行缓存清除)

谢谢你:)

假设您使用的是版本 5,Webpack asset modules will provide what you want without the need for copy-webpack-plugin. Webpack can recognize a require statement with expressions。 Webpack 将自动为您包含所有可能匹配的文件,无需额外配置。在这种情况下,您可能需要注意 Webpack 知道名称设置为“tiles”的优化。这是您的配置所需的补充:

module.exports = {
   module: {
      rules: [
          {
              test: /data\/json\/.+\.json$/
              type: 'asset/resource',
              generator: {
                  // Look at https://webpack.js.org/configuration/output/#template-strings to see additional template strings.
                  filename: '[path][name].[hash:6][ext]'
              }
          }
      ]
   }
}

或者,对于 Webpack 4,您可以添加 file-loader 作为依赖项,并将其与等效的配置添加一起使用:

module.exports = {
   module: {
      rules: [
          {
              test: /data\/json\/.+\.json$/
              loader: 'file-loader',
              options: {
                  name: '[path][name].[hash:6][ext]'
              }
          }
      ]
   }
}

无论哪种方式,您的代码现在都可以按如下方式简单地工作:

let name = "tiles";
const tileDataUrl = require(`data/json/${name}.json`); // tileDataUrl will display the interpolated filename.
fetch(tileDataUrl);