diff --git a/lib/library/AssignLibraryPlugin.js b/lib/library/AssignLibraryPlugin.js index 9a67c60c5..0b40f3fbf 100644 --- a/lib/library/AssignLibraryPlugin.js +++ b/lib/library/AssignLibraryPlugin.js @@ -29,21 +29,43 @@ const accessWithInit = (accessor, existingLength, initLast = false) => { // This generates for [a, b, c, d]: // (((a = typeof a === "undefined" ? {} : a).b = a.b || {}).c = a.b.c || {}).d const base = accessor[0]; + if (accessor.length === 1 && !initLast) return base; let current = - existingLength > 0 || (!initLast && accessor.length === 1) + existingLength > 0 ? base : `(${base} = typeof ${base} === "undefined" ? {} : ${base})`; - let propsSoFar = accessor.slice(1, existingLength); - current += propertyAccess(propsSoFar); - if (existingLength >= accessor.length - 1) return current; - for (let i = Math.max(1, existingLength); i < accessor.length - 1; i++) { + + // i is the current position in accessor that has been printed + let i = 1; + + // all properties printed so far (excluding base) + let propsSoFar; + + // if there is existingLength, print all properties until this position as property access + if (existingLength > i) { + propsSoFar = accessor.slice(1, existingLength); + i = existingLength; + current += propertyAccess(propsSoFar); + } else { + propsSoFar = []; + } + + // all remainig properties (except the last one when initLast is not set) + // should be printed as initializer + const initUntil = initLast ? accessor.length : accessor.length - 1; + for (; i < initUntil; i++) { const prop = accessor[i]; propsSoFar.push(prop); current = `(${current}${propertyAccess([prop])} = ${base}${propertyAccess( propsSoFar )} || {})`; } - return `${current}${propertyAccess([accessor[accessor.length - 1]])}`; + + // print the last property as property access if not yet printed + if (i < accessor.length) + current = `${current}${propertyAccess([accessor[accessor.length - 1]])}`; + + return current; }; /**