web-infra-dev / rspack

The fast Rust-based web bundler with webpack-compatible API 🦀️
https://rspack.dev
MIT License
8.45k stars 498 forks source link

[Feature]: localVars hook to support RetryChunkPlugin #6837

Open zackarychapple opened 1 month ago

zackarychapple commented 1 month ago

What problem does this feature solve?

When trying to use webpack-retry-chunk-load-plugin the build fails because of a missing hook.

What does the proposed API of configuration look like?

Bring through the localVars hook to support RetryChunkPlugin

ScriptedAlchemy commented 1 month ago

You can patch the same functionality without a plugin with something like this. Just put it at the top of your entrypoint and that should work.

(function() {
  // Save the original __webpack_require__.e function
  var originalEnsure = __webpack_require__.e;

  // Create a retry wrapper around the original ensure function
  function retryEnsure(chunkId, retries = 3) {
    function tryEnsure(attempt) {
      return originalEnsure(chunkId).catch(error => {
        if (attempt < retries) {
          console.warn(`Retrying to load chunk ${chunkId}, attempt ${attempt}`);
          return tryEnsure(attempt + 1);
        } else {
          console.error(`Failed to load chunk ${chunkId} after ${retries} attempts`);
          throw error;
        }
      });
    }
    return tryEnsure(1);
  }

  // Patch the original __webpack_require__.e function
  __webpack_require__.e = function(chunkId) {
    return retryEnsure(chunkId);
  };

  // If there are any additional properties or methods on __webpack_require__.e, copy them over
  for (var key in originalEnsure) {
    if (originalEnsure.hasOwnProperty(key)) {
      __webpack_require__.e[key] = originalEnsure[key];
    }
  }
})();
zackarychapple commented 1 month ago

This is actually a duplicate of this #4602

chenjiahan commented 1 month ago

@SoonIter Can you refer to this implementation? Maybe it will be helpful for Rsbuild's assets retry plugin

SoonIter commented 1 month ago

This part of code seems to be marked and will be deprecated in webpack6. https://webpack.js.org/blog/2020-10-10-webpack-5-release/#mainchunkmoduletemplate-deprecation https://github.com/webpack/webpack/blob/77a4398a907970a4bac66b45370806a8ec5e047c/lib/MainTemplate.js#L40

So the backup hooks maybe https://github.com/web-infra-dev/rspack/pull/5370

I reimplemented this plugin of Rspack in Rsbuild, at present, this plugin has not been exposed to users of rspack. https://github.com/web-infra-dev/rsbuild/blob/85a7ced8287ed21c376dce51ee5fca94110fe187/packages/plugin-assets-retry/src/AsyncChunkRetryPlugin.ts#L88 https://github.com/web-infra-dev/rsbuild/pull/2086

I think we need webpack-retry-loading-plugin to adjust the implementation, or we can provide a rspack-retry-loading-plugin.

zackarychapple commented 1 month ago

Luckily @hardfist did a little work to get us moving again and created this rspack-retry-chunk