Skip to content

Commit

Permalink
feat: add lastResortScript option
Browse files Browse the repository at this point in the history
  • Loading branch information
k41n authored Jun 26, 2020
1 parent 0df71c8 commit 0d1e570
Show file tree
Hide file tree
Showing 4 changed files with 269 additions and 2 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ plugins: [
maxRetries: 5,
// optional list of chunks to which retry script should be injected
// if not set will add retry script to all chunks that have webpack script loading
chunks: ['chunkName']
chunks: ['chunkName'],
// optional code to be executed in the browser context if after all retries chunk is not loaded.
// if not set - nothing will happen and error will be returned to the chunk loader.
lastResortScript: "window.location.href='/500.html'";
})
];
```
Expand Down
6 changes: 5 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,11 @@ class RetryChunkLoadPlugin {
error.message = 'Loading chunk ' + chunkId + ' failed after ${maxRetries} retries.\\n(' + errorType + ': ' + realSrc + ')';
error.name = 'ChunkLoadError';
error.type = errorType;
error.request = realSrc;
error.request = realSrc;${
this.options.lastResortScript
? this.options.lastResortScript
: ''
}
chunk[1](error);
installedChunks[chunkId] = undefined;
} else {
Expand Down
250 changes: 250 additions & 0 deletions test/integration/__snapshots__/test.js.snap
Original file line number Diff line number Diff line change
@@ -1,5 +1,255 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`inserts last resort script into the code handling failure after all retries 1`] = `
"/******/ (function(modules) { // webpackBootstrap
/******/ // install a JSONP callback for chunk loading
/******/ function webpackJsonpCallback(data) {
/******/ var chunkIds = data[0];
/******/ var moreModules = data[1];
/******/
/******/
/******/ // add \\"moreModules\\" to the modules object,
/******/ // then flag all \\"chunkIds\\" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0, resolves = [];
/******/ for(;i < chunkIds.length; i++) {
/******/ chunkId = chunkIds[i];
/******/ if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ resolves.push(installedChunks[chunkId][0]);
/******/ }
/******/ installedChunks[chunkId] = 0;
/******/ }
/******/ for(moduleId in moreModules) {
/******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
/******/ modules[moduleId] = moreModules[moduleId];
/******/ }
/******/ }
/******/ if(parentJsonpFunction) parentJsonpFunction(data);
/******/
/******/ while(resolves.length) {
/******/ resolves.shift()();
/******/ }
/******/
/******/ };
/******/
/******/
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // object to store loaded and loading chunks
/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ // Promise = chunk loading, 0 = chunk loaded
/******/ var installedChunks = {
/******/ \\"main\\": 0
/******/ };
/******/
/******/
/******/
/******/ // script path function
/******/ function jsonpScriptSrc(chunkId) {
/******/ return __webpack_require__.p + \\"\\" + ({}[chunkId]||chunkId) + \\".js\\"
/******/ }
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/ // This file contains only the entry chunk.
/******/ // The chunk loading function for additional chunks
/******/ __webpack_require__.e = function requireEnsure(chunkId) {
/******/ var promises = [];
/******/
/******/
/******/ // JSONP chunk loading for javascript
/******/
/******/ var installedChunkData = installedChunks[chunkId];
/******/ if(installedChunkData !== 0) { // 0 means \\"already installed\\".
/******/
/******/ // a Promise means \\"currently loading\\".
/******/ if(installedChunkData) {
/******/ promises.push(installedChunkData[2]);
/******/ } else {
/******/ // setup Promise in chunk cache
/******/ var promise = new Promise(function(resolve, reject) {
/******/ installedChunkData = installedChunks[chunkId] = [resolve, reject];
/******/ });
/******/ promises.push(installedChunkData[2] = promise);
/******/
/******/ // start chunk loading
/******/ // create error before stack unwound to get useful stacktrace later
/******/ var error = new Error();
/******/ function loadScript(src, retries) {
/******/ var script = document.createElement('script');
/******/ var retryAttempt = 1 - retries + 1;
/******/ var retryAttemptString = '&retry-attempt=' + retryAttempt;
/******/ var onScriptComplete;
/******/
/******/ script.charset = 'utf-8';
/******/ script.timeout = 120;
/******/ if (__webpack_require__.nc) {
/******/ script.setAttribute('nonce', __webpack_require__.nc);
/******/ }
/******/ script.src = src;
/******/
/******/ onScriptComplete = function(event) {
/******/ // avoid mem leaks in IE.
/******/ script.onerror = script.onload = null;
/******/ clearTimeout(timeout);
/******/ var chunk = installedChunks[chunkId];
/******/ if (chunk !== 0) {
/******/ if (chunk) {
/******/ if (retries === 0) {
/******/ var errorType =
/******/ event && (event.type === 'load' ? 'missing' : event.type);
/******/ var realSrc = event && event.target && event.target.src;
/******/ error.message =
/******/ 'Loading chunk ' +
/******/ chunkId +
/******/ ' failed after 1 retries.\\\\n(' +
/******/ errorType +
/******/ ': ' +
/******/ realSrc +
/******/ ')';
/******/ error.name = 'ChunkLoadError';
/******/ error.type = errorType;
/******/ error.request = realSrc;
/******/ window.location.href = '/500.html';
/******/ chunk[1](error);
/******/ installedChunks[chunkId] = undefined;
/******/ } else {
/******/ var cacheBust = 'cache-bust=true' + retryAttemptString;
/******/ var retryScript = loadScript(
/******/ jsonpScriptSrc(chunkId) + '?' + cacheBust,
/******/ retries - 1
/******/ );
/******/ document.head.appendChild(retryScript);
/******/ }
/******/ } else {
/******/ installedChunks[chunkId] = undefined;
/******/ }
/******/ }
/******/ };
/******/ var timeout = setTimeout(function() {
/******/ onScriptComplete({ type: 'timeout', target: script });
/******/ }, 120000);
/******/ script.onerror = script.onload = onScriptComplete;
/******/ return script;
/******/ }
/******/
/******/ var script = loadScript(jsonpScriptSrc(chunkId), 1);
/******/ document.head.appendChild(script);
/******/ }
/******/ }
/******/ return Promise.all(promises);
/******/ };
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = \\"\\";
/******/
/******/ // on error function for async loading
/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };
/******/
/******/ var jsonpArray = window[\\"webpackJsonp\\"] = window[\\"webpackJsonp\\"] || [];
/******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray);
/******/ jsonpArray.push = webpackJsonpCallback;
/******/ jsonpArray = jsonpArray.slice();
/******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]);
/******/ var parentJsonpFunction = oldJsonpFunction;
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = \\"./test/integration/fixtures/index.js\\");
/******/ })
/************************************************************************/
/******/ ({
/***/ \\"./test/integration/fixtures/index.js\\":
/*!********************************************!*\\\\
!*** ./test/integration/fixtures/index.js ***!
\\\\********************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
async function run() {
console.log(await __webpack_require__.e(/*! import() */ 0).then(__webpack_require__.bind(null, /*! ./async */ \\"./test/integration/fixtures/async.js\\")));
}
run();
/***/ })
/******/ });"
`;

exports[`override the default jsonp script 1`] = `
"/******/ (function(modules) { // webpackBootstrap
/******/ // install a JSONP callback for chunk loading
Expand Down
10 changes: 10 additions & 0 deletions test/integration/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,13 @@ test('retry loading the main chunk', async () => {
const mainContents = fs.readFileSync(mainOutputFile).toString();
expect(mainContents).toMatchSnapshot();
});

test('inserts last resort script into the code handling failure after all retries', async () => {
const { result, fs } = webpack({
chunks: ['main'],
lastResortScript: "window.location.href='/500.html'"
});
await result;
const mainContents = fs.readFileSync(mainOutputFile).toString();
expect(mainContents).toMatchSnapshot();
});

0 comments on commit 0d1e570

Please sign in to comment.