diff --git a/examples/template-common.js b/examples/template-common.js index c68c5ac1d..2e5a9db18 100644 --- a/examples/template-common.js +++ b/examples/template-common.js @@ -60,7 +60,7 @@ exports.replaceResults = (template, baseDir, stdout, prefix) => { const regexp = new RegExp("_\\{\\{" + (prefix ? prefix + ":" : "") + "([^:\\}]+)\\}\\}_", "g"); return template.replace(regexp, function(match) { - match = match.substr(3 + (prefix ? prefix.length + 1 : 0), match.length - 6 - (prefix ? prefix.length + 1 : 0)); + match = match.slice(3 + (prefix ? prefix.length + 1 : 0), -3); if(match === "stdout") return stdout; try { diff --git a/hot/poll.js b/hot/poll.js index dab215a42..9635447ee 100644 --- a/hot/poll.js +++ b/hot/poll.js @@ -4,7 +4,7 @@ */ /*globals __resourceQuery */ if (module.hot) { - var hotPollInterval = +__resourceQuery.substr(1) || 10 * 60 * 1000; + var hotPollInterval = +__resourceQuery.slice(1) || 10 * 60 * 1000; var log = require("./log"); var checkForUpdate = function checkForUpdate(fromUpdate) { diff --git a/hot/signal.js b/hot/signal.js index ef949521f..f1d59c8f1 100644 --- a/hot/signal.js +++ b/hot/signal.js @@ -45,7 +45,7 @@ if (module.hot) { }); }; - process.on(__resourceQuery.substr(1) || "SIGUSR2", function () { + process.on(__resourceQuery.slice(1) || "SIGUSR2", function () { if (module.hot.status() !== "idle") { log( "warning", diff --git a/lib/Chunk.js b/lib/Chunk.js index db598c70b..51a018ed8 100644 --- a/lib/Chunk.js +++ b/lib/Chunk.js @@ -690,7 +690,7 @@ class Chunk { for (const childGroup of group.childrenIterable) { for (const key of Object.keys(childGroup.options)) { if (key.endsWith("Order")) { - const name = key.substr(0, key.length - "Order".length); + const name = key.slice(0, key.length - "Order".length); let list = lists.get(name); if (list === undefined) { list = []; diff --git a/lib/ChunkGroup.js b/lib/ChunkGroup.js index 69b2128a3..78167ed44 100644 --- a/lib/ChunkGroup.js +++ b/lib/ChunkGroup.js @@ -486,7 +486,7 @@ class ChunkGroup { for (const childGroup of this._children) { for (const key of Object.keys(childGroup.options)) { if (key.endsWith("Order")) { - const name = key.substr(0, key.length - "Order".length); + const name = key.slice(0, key.length - "Order".length); let list = lists.get(name); if (list === undefined) { lists.set(name, (list = [])); diff --git a/lib/Compilation.js b/lib/Compilation.js index 35e4018f1..6e73dc3af 100644 --- a/lib/Compilation.js +++ b/lib/Compilation.js @@ -3896,7 +3896,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o module, runtime, digest, - digest.substr(0, hashDigestLength) + digest.slice(0, hashDigestLength) ); statModulesFromCache++; continue; @@ -3960,7 +3960,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o module, runtime, moduleHashDigest, - moduleHashDigest.substr(0, hashDigestLength) + moduleHashDigest.slice(0, hashDigestLength) ); return moduleHashDigest; } @@ -4164,7 +4164,7 @@ This prevents using hashes of each other and should be avoided.`); ); hash.update(chunkHashDigest); chunk.hash = chunkHashDigest; - chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); + chunk.renderedHash = chunk.hash.slice(0, hashDigestLength); const fullHashModules = chunkGraph.getChunkFullHashModulesIterable(chunk); if (fullHashModules) { @@ -4191,7 +4191,7 @@ This prevents using hashes of each other and should be avoided.`); this.logger.time("hashing: hash digest"); this.hooks.fullHash.call(hash); this.fullHash = /** @type {string} */ (hash.digest(hashDigest)); - this.hash = this.fullHash.substr(0, hashDigestLength); + this.hash = this.fullHash.slice(0, hashDigestLength); this.logger.timeEnd("hashing: hash digest"); this.logger.time("hashing: process full hash modules"); @@ -4211,7 +4211,7 @@ This prevents using hashes of each other and should be avoided.`); module, chunk.runtime, moduleHashDigest, - moduleHashDigest.substr(0, hashDigestLength) + moduleHashDigest.slice(0, hashDigestLength) ); codeGenerationJobsMap.get(oldHash).get(module).hash = moduleHashDigest; } @@ -4222,7 +4222,7 @@ This prevents using hashes of each other and should be avoided.`); chunkHash.digest(hashDigest) ); chunk.hash = chunkHashDigest; - chunk.renderedHash = chunk.hash.substr(0, hashDigestLength); + chunk.renderedHash = chunk.hash.slice(0, hashDigestLength); this.hooks.contentHash.call(chunk); } this.logger.timeEnd("hashing: process full hash modules"); diff --git a/lib/Compiler.js b/lib/Compiler.js index 9bf57f028..bd7474d8f 100644 --- a/lib/Compiler.js +++ b/lib/Compiler.js @@ -596,7 +596,7 @@ class Compiler { let immutable = info.immutable; const queryStringIdx = targetFile.indexOf("?"); if (queryStringIdx >= 0) { - targetFile = targetFile.substr(0, queryStringIdx); + targetFile = targetFile.slice(0, queryStringIdx); // We may remove the hash, which is in the query string // So we recheck if the file is immutable // This doesn't cover all cases, but immutable is only a performance optimization anyway diff --git a/lib/ConstPlugin.js b/lib/ConstPlugin.js index 844da0c6f..e9d776f08 100644 --- a/lib/ConstPlugin.js +++ b/lib/ConstPlugin.js @@ -324,7 +324,7 @@ class ConstPlugin { } } else if (expression.operator === "??") { const param = parser.evaluateExpression(expression.left); - const keepRight = param && param.asNullish(); + const keepRight = param.asNullish(); if (typeof keepRight === "boolean") { // ------------------------------------------ // @@ -407,7 +407,7 @@ class ConstPlugin { const expression = optionalExpressionsStack.pop(); const evaluated = parser.evaluateExpression(expression); - if (evaluated && evaluated.asNullish()) { + if (evaluated.asNullish()) { // ------------------------------------------ // // Given the following code: diff --git a/lib/ContextModuleFactory.js b/lib/ContextModuleFactory.js index dac23100a..9bd50d916 100644 --- a/lib/ContextModuleFactory.js +++ b/lib/ContextModuleFactory.js @@ -128,7 +128,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory { loadersPrefix = ""; const idx = request.lastIndexOf("!"); if (idx >= 0) { - let loadersRequest = request.substr(0, idx + 1); + let loadersRequest = request.slice(0, idx + 1); let i; for ( i = 0; @@ -138,7 +138,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory { loadersPrefix += "!"; } loadersRequest = loadersRequest - .substr(i) + .slice(i) .replace(/!+$/, "") .replace(/!!+/g, "!"); if (loadersRequest === "") { @@ -146,7 +146,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory { } else { loaders = loadersRequest.split("!"); } - resource = request.substr(idx + 1); + resource = request.slice(idx + 1); } else { loaders = []; resource = request; @@ -348,7 +348,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory { const obj = { context: ctx, request: - "." + subResource.substr(ctx.length).replace(/\\/g, "/") + "." + subResource.slice(ctx.length).replace(/\\/g, "/") }; this.hooks.alternativeRequests.callAsync( diff --git a/lib/DelegatedModuleFactoryPlugin.js b/lib/DelegatedModuleFactoryPlugin.js index 1614c74ae..914db2e4f 100644 --- a/lib/DelegatedModuleFactoryPlugin.js +++ b/lib/DelegatedModuleFactoryPlugin.js @@ -29,7 +29,7 @@ class DelegatedModuleFactoryPlugin { const [dependency] = data.dependencies; const { request } = dependency; if (request && request.startsWith(`${scope}/`)) { - const innerRequest = "." + request.substr(scope.length); + const innerRequest = "." + request.slice(scope.length); let resolved; if (innerRequest in this.options.content) { resolved = this.options.content[innerRequest]; diff --git a/lib/ErrorHelpers.js b/lib/ErrorHelpers.js index 7851bdc8e..66032a849 100644 --- a/lib/ErrorHelpers.js +++ b/lib/ErrorHelpers.js @@ -43,8 +43,8 @@ exports.cutOffMessage = (stack, message) => { if (nextLine === -1) { return stack === message ? "" : stack; } else { - const firstLine = stack.substr(0, nextLine); - return firstLine === message ? stack.substr(nextLine + 1) : stack; + const firstLine = stack.slice(0, nextLine); + return firstLine === message ? stack.slice(nextLine + 1) : stack; } }; diff --git a/lib/ExternalModuleFactoryPlugin.js b/lib/ExternalModuleFactoryPlugin.js index 92d564700..5dae85c71 100644 --- a/lib/ExternalModuleFactoryPlugin.js +++ b/lib/ExternalModuleFactoryPlugin.js @@ -89,8 +89,8 @@ class ExternalModuleFactoryPlugin { UNSPECIFIED_EXTERNAL_TYPE_REGEXP.test(externalConfig) ) { const idx = externalConfig.indexOf(" "); - type = externalConfig.substr(0, idx); - externalConfig = externalConfig.substr(idx + 1); + type = externalConfig.slice(0, idx); + externalConfig = externalConfig.slice(idx + 1); } else if ( Array.isArray(externalConfig) && externalConfig.length > 0 && @@ -98,9 +98,9 @@ class ExternalModuleFactoryPlugin { ) { const firstItem = externalConfig[0]; const idx = firstItem.indexOf(" "); - type = firstItem.substr(0, idx); + type = firstItem.slice(0, idx); externalConfig = [ - firstItem.substr(idx + 1), + firstItem.slice(idx + 1), ...externalConfig.slice(1) ]; } diff --git a/lib/LoaderOptionsPlugin.js b/lib/LoaderOptionsPlugin.js index a96c5bb7d..45fb88662 100644 --- a/lib/LoaderOptionsPlugin.js +++ b/lib/LoaderOptionsPlugin.js @@ -52,7 +52,7 @@ class LoaderOptionsPlugin { if ( ModuleFilenameHelpers.matchObject( options, - i < 0 ? resource : resource.substr(0, i) + i < 0 ? resource : resource.slice(0, i) ) ) { for (const key of Object.keys(options)) { diff --git a/lib/ModuleFilenameHelpers.js b/lib/ModuleFilenameHelpers.js index 610615d82..2b6afc114 100644 --- a/lib/ModuleFilenameHelpers.js +++ b/lib/ModuleFilenameHelpers.js @@ -47,7 +47,7 @@ const getAfter = (strFn, token) => { return () => { const str = strFn(); const idx = str.indexOf(token); - return idx < 0 ? "" : str.substr(idx); + return idx < 0 ? "" : str.slice(idx); }; }; @@ -55,7 +55,7 @@ const getBefore = (strFn, token) => { return () => { const str = strFn(); const idx = str.lastIndexOf(token); - return idx < 0 ? "" : str.substr(0, idx); + return idx < 0 ? "" : str.slice(0, idx); }; }; @@ -64,7 +64,7 @@ const getHash = (strFn, hashFunction) => { const hash = createHash(hashFunction); hash.update(strFn()); const digest = /** @type {string} */ (hash.digest("hex")); - return digest.substr(0, 4); + return digest.slice(0, 4); }; }; diff --git a/lib/NormalModule.js b/lib/NormalModule.js index 5484e1957..5e8dbded4 100644 --- a/lib/NormalModule.js +++ b/lib/NormalModule.js @@ -375,7 +375,7 @@ class NormalModule extends Module { nameForCondition() { const resource = this.matchResource || this.resource; const idx = resource.indexOf("?"); - if (idx >= 0) return resource.substr(0, idx); + if (idx >= 0) return resource.slice(0, idx); return resource; } @@ -558,7 +558,7 @@ class NormalModule extends Module { let { options } = loader; if (typeof options === "string") { - if (options.substr(0, 1) === "{" && options.substr(-1) === "}") { + if (options.startsWith("{") && options.endsWith("}")) { try { options = parseJson(options); } catch (e) { diff --git a/lib/NormalModuleFactory.js b/lib/NormalModuleFactory.js index a6895d7e5..f02e57128 100644 --- a/lib/NormalModuleFactory.js +++ b/lib/NormalModuleFactory.js @@ -379,7 +379,7 @@ class NormalModuleFactory extends ModuleFactory { resource: matchResource, ...cacheParseResource(matchResource) }; - requestWithoutMatchResource = request.substr( + requestWithoutMatchResource = request.slice( matchResourceMatch[0].length ); } @@ -437,7 +437,7 @@ class NormalModuleFactory extends ModuleFactory { try { for (const item of loaders) { if (typeof item.options === "string" && item.options[0] === "?") { - const ident = item.options.substr(1); + const ident = item.options.slice(1); if (ident === "[[missing ident]]") { throw new Error( "No ident is provided by referenced loader. " + diff --git a/lib/RuntimePlugin.js b/lib/RuntimePlugin.js index 6d33a8ab9..3e0fc6e4e 100644 --- a/lib/RuntimePlugin.js +++ b/lib/RuntimePlugin.js @@ -11,6 +11,7 @@ const RuntimeRequirementsDependency = require("./dependencies/RuntimeRequirement const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin"); const AsyncModuleRuntimeModule = require("./runtime/AsyncModuleRuntimeModule"); const AutoPublicPathRuntimeModule = require("./runtime/AutoPublicPathRuntimeModule"); +const BaseUriRuntimeModule = require("./runtime/BaseUriRuntimeModule"); const CompatGetDefaultExportRuntimeModule = require("./runtime/CompatGetDefaultExportRuntimeModule"); const CompatRuntimeModule = require("./runtime/CompatRuntimeModule"); const CreateFakeNamespaceObjectRuntimeModule = require("./runtime/CreateFakeNamespaceObjectRuntimeModule"); @@ -96,6 +97,15 @@ class RuntimePlugin { */ apply(compiler) { compiler.hooks.compilation.tap("RuntimePlugin", compilation => { + const globalChunkLoading = compilation.outputOptions.chunkLoading; + const isChunkLoadingDisabledForChunk = chunk => { + const options = chunk.getEntryOptions(); + const chunkLoading = + options && options.chunkLoading !== undefined + ? options.chunkLoading + : globalChunkLoading; + return chunkLoading === false; + }; compilation.dependencyTemplates.set( RuntimeRequirementsDependency, new RuntimeRequirementsDependency.Template() @@ -413,6 +423,14 @@ class RuntimePlugin { ); return true; }); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.baseURI) + .tap("RuntimePlugin", chunk => { + if (isChunkLoadingDisabledForChunk(chunk)) { + compilation.addRuntimeModule(chunk, new BaseUriRuntimeModule()); + return true; + } + }); // TODO webpack 6: remove CompatRuntimeModule compilation.hooks.additionalTreeRuntimeRequirements.tap( "RuntimePlugin", diff --git a/lib/config/defaults.js b/lib/config/defaults.js index bfc8b2975..bd91b469d 100644 --- a/lib/config/defaults.js +++ b/lib/config/defaults.js @@ -715,7 +715,15 @@ const applyOutputDefaults = ( }; F(output, "uniqueName", () => { - const libraryName = getLibraryName(output.library); + const libraryName = getLibraryName(output.library).replace( + /^\[(\\*[\w:]+\\*)\](\.)|(\.)\[(\\*[\w:]+\\*)\](?=\.|$)|\[(\\*[\w:]+\\*)\]/g, + (m, a, d1, d2, b, c) => { + const content = a || b || c; + return content.startsWith("\\") && content.endsWith("\\") + ? `${d2 || ""}[${content.slice(1, -1)}]${d1 || ""}` + : ""; + } + ); if (libraryName) return libraryName; const pkgPath = path.resolve(context, "package.json"); try { diff --git a/lib/dependencies/CommonJsExportsParserPlugin.js b/lib/dependencies/CommonJsExportsParserPlugin.js index a0be15e26..adccb109a 100644 --- a/lib/dependencies/CommonJsExportsParserPlugin.js +++ b/lib/dependencies/CommonJsExportsParserPlugin.js @@ -201,7 +201,7 @@ class CommonJsExportsParserPlugin { if (expr.arguments[1].type === "SpreadElement") return; if (expr.arguments[2].type === "SpreadElement") return; const exportsArg = parser.evaluateExpression(expr.arguments[0]); - if (!exportsArg || !exportsArg.isIdentifier()) return; + if (!exportsArg.isIdentifier()) return; if ( exportsArg.identifier !== "exports" && exportsArg.identifier !== "module.exports" && @@ -210,7 +210,6 @@ class CommonJsExportsParserPlugin { return; } const propertyArg = parser.evaluateExpression(expr.arguments[1]); - if (!propertyArg) return; const property = propertyArg.asString(); if (typeof property !== "string") return; enableStructuredExports(); diff --git a/lib/dependencies/ContextDependencyHelpers.js b/lib/dependencies/ContextDependencyHelpers.js index 488ed9a1d..45d865242 100644 --- a/lib/dependencies/ContextDependencyHelpers.js +++ b/lib/dependencies/ContextDependencyHelpers.js @@ -28,8 +28,8 @@ const splitContextFromPrefix = prefix => { const idx = prefix.lastIndexOf("/"); let context = "."; if (idx >= 0) { - context = prefix.substr(0, idx); - prefix = `.${prefix.substr(idx)}`; + context = prefix.slice(0, idx); + prefix = `.${prefix.slice(idx)}`; } return { context, diff --git a/lib/dependencies/HarmonyImportDependencyParserPlugin.js b/lib/dependencies/HarmonyImportDependencyParserPlugin.js index c0c1f6896..7e5c9cdb7 100644 --- a/lib/dependencies/HarmonyImportDependencyParserPlugin.js +++ b/lib/dependencies/HarmonyImportDependencyParserPlugin.js @@ -83,6 +83,18 @@ module.exports = class HarmonyImportDependencyParserPlugin { */ apply(parser) { const { exportPresenceMode } = this; + + function getNonOptionalPart(members, membersOptionals) { + let i = 0; + while (i < members.length && membersOptionals[i] === false) i++; + return i !== members.length ? members.slice(0, i) : members; + } + + function getNonOptionalMemberChain(node, count) { + while (count--) node = node.object; + return node; + } + parser.hooks.isPure .for("Identifier") .tap("HarmonyImportDependencyParserPlugin", expression => { @@ -154,51 +166,83 @@ module.exports = class HarmonyImportDependencyParserPlugin { }); parser.hooks.expressionMemberChain .for(harmonySpecifierTag) - .tap("HarmonyImportDependencyParserPlugin", (expr, members) => { - const settings = /** @type {HarmonySettings} */ (parser.currentTagData); - const ids = settings.ids.concat(members); - const dep = new HarmonyImportSpecifierDependency( - settings.source, - settings.sourceOrder, - ids, - settings.name, - expr.range, - exportPresenceMode, - settings.assertions - ); - dep.asiSafe = !parser.isAsiPosition(expr.range[0]); - dep.loc = expr.loc; - parser.state.module.addDependency(dep); - InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); - return true; - }); + .tap( + "HarmonyImportDependencyParserPlugin", + (expression, members, membersOptionals) => { + const settings = /** @type {HarmonySettings} */ ( + parser.currentTagData + ); + const nonOptionalMembers = getNonOptionalPart( + members, + membersOptionals + ); + const expr = + nonOptionalMembers !== members + ? getNonOptionalMemberChain( + expression, + members.length - nonOptionalMembers.length + ) + : expression; + const ids = settings.ids.concat(nonOptionalMembers); + const dep = new HarmonyImportSpecifierDependency( + settings.source, + settings.sourceOrder, + ids, + settings.name, + expr.range, + exportPresenceMode, + settings.assertions + ); + dep.asiSafe = !parser.isAsiPosition(expr.range[0]); + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); + return true; + } + ); parser.hooks.callMemberChain .for(harmonySpecifierTag) - .tap("HarmonyImportDependencyParserPlugin", (expr, members) => { - const { arguments: args, callee } = expr; - const settings = /** @type {HarmonySettings} */ (parser.currentTagData); - const ids = settings.ids.concat(members); - const dep = new HarmonyImportSpecifierDependency( - settings.source, - settings.sourceOrder, - ids, - settings.name, - callee.range, - exportPresenceMode, - settings.assertions - ); - dep.directImport = members.length === 0; - dep.call = true; - dep.asiSafe = !parser.isAsiPosition(callee.range[0]); - // only in case when we strictly follow the spec we need a special case here - dep.namespaceObjectAsContext = - members.length > 0 && this.strictThisContextOnImports; - dep.loc = callee.loc; - parser.state.module.addDependency(dep); - if (args) parser.walkExpressions(args); - InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); - return true; - }); + .tap( + "HarmonyImportDependencyParserPlugin", + (expression, members, membersOptionals) => { + const { arguments: args, callee } = expression; + const settings = /** @type {HarmonySettings} */ ( + parser.currentTagData + ); + const nonOptionalMembers = getNonOptionalPart( + members, + membersOptionals + ); + const expr = + nonOptionalMembers !== members + ? getNonOptionalMemberChain( + callee, + members.length - nonOptionalMembers.length + ) + : callee; + const ids = settings.ids.concat(nonOptionalMembers); + const dep = new HarmonyImportSpecifierDependency( + settings.source, + settings.sourceOrder, + ids, + settings.name, + expr.range, + exportPresenceMode, + settings.assertions + ); + dep.directImport = members.length === 0; + dep.call = true; + dep.asiSafe = !parser.isAsiPosition(expr.range[0]); + // only in case when we strictly follow the spec we need a special case here + dep.namespaceObjectAsContext = + members.length > 0 && this.strictThisContextOnImports; + dep.loc = expr.loc; + parser.state.module.addDependency(dep); + if (args) parser.walkExpressions(args); + InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e)); + return true; + } + ); const { hotAcceptCallback, hotAcceptWithoutCallback } = HotModuleReplacementPlugin.getParserHooks(parser); hotAcceptCallback.tap( diff --git a/lib/ids/HashedModuleIdsPlugin.js b/lib/ids/HashedModuleIdsPlugin.js index 585e12cff..4e8ff4225 100644 --- a/lib/ids/HashedModuleIdsPlugin.js +++ b/lib/ids/HashedModuleIdsPlugin.js @@ -64,8 +64,8 @@ class HashedModuleIdsPlugin { hash.digest(options.hashDigest) ); let len = options.hashDigestLength; - while (usedIds.has(hashId.substr(0, len))) len++; - const moduleId = hashId.substr(0, len); + while (usedIds.has(hashId.slice(0, len))) len++; + const moduleId = hashId.slice(0, len); chunkGraph.setModuleId(module, moduleId); usedIds.add(moduleId); } diff --git a/lib/ids/IdHelpers.js b/lib/ids/IdHelpers.js index 9e011cf8b..e674a4484 100644 --- a/lib/ids/IdHelpers.js +++ b/lib/ids/IdHelpers.js @@ -25,7 +25,7 @@ const getHash = (str, len, hashFunction) => { const hash = createHash(hashFunction); hash.update(str); const digest = /** @type {string} */ (hash.digest("hex")); - return digest.substr(0, len); + return digest.slice(0, len); }; /** diff --git a/lib/javascript/BasicEvaluatedExpression.js b/lib/javascript/BasicEvaluatedExpression.js index 0e5a21183..b7eb648e9 100644 --- a/lib/javascript/BasicEvaluatedExpression.js +++ b/lib/javascript/BasicEvaluatedExpression.js @@ -67,6 +67,8 @@ class BasicEvaluatedExpression { this.rootInfo = undefined; /** @type {() => string[]} */ this.getMembers = undefined; + /** @type {() => boolean[]} */ + this.getMembersOptionals = undefined; /** @type {EsTreeNode} */ this.expression = undefined; } @@ -342,11 +344,12 @@ class BasicEvaluatedExpression { return this; } - setIdentifier(identifier, rootInfo, getMembers) { + setIdentifier(identifier, rootInfo, getMembers, getMembersOptionals) { this.type = TypeIdentifier; this.identifier = identifier; this.rootInfo = rootInfo; this.getMembers = getMembers; + this.getMembersOptionals = getMembersOptionals; this.sideEffects = true; return this; } diff --git a/lib/javascript/JavascriptParser.js b/lib/javascript/JavascriptParser.js index 93050a635..ad6220ff1 100644 --- a/lib/javascript/JavascriptParser.js +++ b/lib/javascript/JavascriptParser.js @@ -57,7 +57,7 @@ const BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); /** @typedef {import("../Parser").ParserState} ParserState */ /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ /** @typedef {{declaredScope: ScopeInfo, freeName: string | true, tagInfo: TagInfo | undefined}} VariableInfoInterface */ -/** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => string[] }} GetInfoResult */ +/** @typedef {{ name: string | VariableInfo, rootInfo: string | VariableInfo, getMembers: () => string[], getMembersOptionals: () => boolean[] }} GetInfoResult */ const EMPTY_ARRAY = []; const ALLOWED_MEMBER_TYPES_CALL_EXPRESSION = 0b01; @@ -262,9 +262,9 @@ class JavascriptParser extends Parser { /** @type {HookMap>} */ call: new HookMap(() => new SyncBailHook(["expression"])), /** Something like "a.b()" */ - /** @type {HookMap>} */ + /** @type {HookMap>} */ callMemberChain: new HookMap( - () => new SyncBailHook(["expression", "members"]) + () => new SyncBailHook(["expression", "members", "membersOptionals"]) ), /** Something like "a.b().c.d" */ /** @type {HookMap>} */ @@ -294,9 +294,9 @@ class JavascriptParser extends Parser { new: new HookMap(() => new SyncBailHook(["expression"])), /** @type {HookMap>} */ expression: new HookMap(() => new SyncBailHook(["expression"])), - /** @type {HookMap>} */ + /** @type {HookMap>} */ expressionMemberChain: new HookMap( - () => new SyncBailHook(["expression", "members"]) + () => new SyncBailHook(["expression", "members", "membersOptionals"]) ), /** @type {HookMap>} */ unhandledExpressionMemberChain: new HookMap( @@ -416,7 +416,6 @@ class JavascriptParser extends Parser { const expr = /** @type {LogicalExpressionNode} */ (_expr); const left = this.evaluateExpression(expr.left); - if (!left) return; let returnRight = false; /** @type {boolean|undefined} */ let allowedRight; @@ -437,7 +436,6 @@ class JavascriptParser extends Parser { returnRight = true; } else return; const right = this.evaluateExpression(expr.right); - if (!right) return; if (returnRight) { if (left.couldHaveSideEffects()) right.setSideEffects(); return right.setRange(expr.range); @@ -486,10 +484,10 @@ class JavascriptParser extends Parser { const handleConstOperation = fn => { const left = this.evaluateExpression(expr.left); - if (!left || !left.isCompileTimeValue()) return; + if (!left.isCompileTimeValue()) return; const right = this.evaluateExpression(expr.right); - if (!right || !right.isCompileTimeValue()) return; + if (!right.isCompileTimeValue()) return; const result = fn( left.asCompileTimeValue(), @@ -545,9 +543,7 @@ class JavascriptParser extends Parser { const handleStrictEqualityComparison = eql => { const left = this.evaluateExpression(expr.left); - if (!left) return; const right = this.evaluateExpression(expr.right); - if (!right) return; const res = new BasicEvaluatedExpression(); res.setRange(expr.range); @@ -600,9 +596,7 @@ class JavascriptParser extends Parser { const handleAbstractEqualityComparison = eql => { const left = this.evaluateExpression(expr.left); - if (!left) return; const right = this.evaluateExpression(expr.right); - if (!right) return; const res = new BasicEvaluatedExpression(); res.setRange(expr.range); @@ -635,9 +629,7 @@ class JavascriptParser extends Parser { if (expr.operator === "+") { const left = this.evaluateExpression(expr.left); - if (!left) return; const right = this.evaluateExpression(expr.right); - if (!right) return; const res = new BasicEvaluatedExpression(); if (left.isString()) { if (right.isString()) { @@ -816,7 +808,7 @@ class JavascriptParser extends Parser { const handleConstOperation = fn => { const argument = this.evaluateExpression(expr.argument); - if (!argument || !argument.isCompileTimeValue()) return; + if (!argument.isCompileTimeValue()) return; const result = fn(argument.asCompileTimeValue()); return valueAsExpression( result, @@ -915,7 +907,6 @@ class JavascriptParser extends Parser { } } else if (expr.operator === "!") { const argument = this.evaluateExpression(expr.argument); - if (!argument) return; const bool = argument.asBool(); if (typeof bool !== "boolean") return; return new BasicEvaluatedExpression() @@ -980,7 +971,12 @@ class JavascriptParser extends Parser { const info = cachedExpression === expr ? cachedInfo : getInfo(expr); if (info !== undefined) { return new BasicEvaluatedExpression() - .setIdentifier(info.name, info.rootInfo, info.getMembers) + .setIdentifier( + info.name, + info.rootInfo, + info.getMembers, + info.getMembersOptionals + ) .setRange(expr.range); } }); @@ -997,7 +993,12 @@ class JavascriptParser extends Parser { typeof info === "string" || (info instanceof VariableInfo && typeof info.freeName === "string") ) { - return { name: info, rootInfo: info, getMembers: () => [] }; + return { + name: info, + rootInfo: info, + getMembers: () => [], + getMembersOptionals: () => [] + }; } }); tapEvaluateWithVariableInfo("ThisExpression", expr => { @@ -1006,7 +1007,12 @@ class JavascriptParser extends Parser { typeof info === "string" || (info instanceof VariableInfo && typeof info.freeName === "string") ) { - return { name: info, rootInfo: info, getMembers: () => [] }; + return { + name: info, + rootInfo: info, + getMembers: () => [], + getMembersOptionals: () => [] + }; } }); this.hooks.evaluate.for("MetaProperty").tap("JavascriptParser", expr => { @@ -1039,7 +1045,6 @@ class JavascriptParser extends Parser { const param = this.evaluateExpression( /** @type {ExpressionNode} */ (expr.callee.object) ); - if (!param) return; const property = expr.callee.property.type === "Literal" ? `${expr.callee.property.value}` @@ -1306,7 +1311,6 @@ class JavascriptParser extends Parser { if (conditionValue === undefined) { const consequent = this.evaluateExpression(expr.consequent); const alternate = this.evaluateExpression(expr.alternate); - if (!consequent || !alternate) return; res = new BasicEvaluatedExpression(); if (consequent.isConditional()) { res.setOptions(consequent.options); @@ -1380,7 +1384,7 @@ class JavascriptParser extends Parser { const expression = optionalExpressionsStack.pop(); const evaluated = this.evaluateExpression(expression); - if (evaluated && evaluated.asNullish()) { + if (evaluated.asNullish()) { return evaluated.setRange(_expr.range); } } @@ -1390,7 +1394,7 @@ class JavascriptParser extends Parser { getRenameIdentifier(expr) { const result = this.evaluateExpression(expr); - if (result && result.isIdentifier()) { + if (result.isIdentifier()) { return result.identifier; } } @@ -2727,7 +2731,10 @@ class JavascriptParser extends Parser { this.hooks.callMemberChain, callee.rootInfo, expression, - callee.getMembers() + callee.getMembers(), + callee.getMembersOptionals + ? callee.getMembersOptionals() + : callee.getMembers().map(() => false) ); if (result1 === true) return; const result2 = this.callHooksForInfo( @@ -2767,11 +2774,13 @@ class JavascriptParser extends Parser { ); if (result1 === true) return; const members = exprInfo.getMembers(); + const membersOptionals = exprInfo.getMembersOptionals(); const result2 = this.callHooksForInfo( this.hooks.expressionMemberChain, exprInfo.rootInfo, expression, - members + members, + membersOptionals ); if (result2 === true) return; this.walkMemberExpressionWithExpressionName( @@ -3167,17 +3176,15 @@ class JavascriptParser extends Parser { /** * @param {ExpressionNode} expression expression node - * @returns {BasicEvaluatedExpression | undefined} evaluation result + * @returns {BasicEvaluatedExpression} evaluation result */ evaluateExpression(expression) { try { const hook = this.hooks.evaluate.get(expression.type); if (hook !== undefined) { const result = hook.call(expression); - if (result !== undefined) { - if (result) { - result.setExpression(expression); - } + if (result !== undefined && result !== null) { + result.setExpression(expression); return result; } } @@ -3348,6 +3355,10 @@ class JavascriptParser extends Parser { return state; } + /** + * @param {string} source source code + * @returns {BasicEvaluatedExpression} evaluation result + */ evaluate(source) { const ast = JavascriptParser._parse("(" + source + ")", { sourceType: this.sourceType, @@ -3609,12 +3620,13 @@ class JavascriptParser extends Parser { /** * @param {MemberExpressionNode} expression a member expression - * @returns {{ members: string[], object: ExpressionNode | SuperNode }} member names (reverse order) and remaining object + * @returns {{ members: string[], object: ExpressionNode | SuperNode, membersOptionals: boolean[] }} member names (reverse order) and remaining object */ extractMemberExpressionChain(expression) { /** @type {AnyNode} */ let expr = expression; const members = []; + const membersOptionals = []; while (expr.type === "MemberExpression") { if (expr.computed) { if (expr.property.type !== "Literal") break; @@ -3623,10 +3635,13 @@ class JavascriptParser extends Parser { if (expr.property.type !== "Identifier") break; members.push(expr.property.name); } + membersOptionals.push(expr.optional); expr = expr.object; } + return { members, + membersOptionals, object: expr }; } @@ -3649,8 +3664,8 @@ class JavascriptParser extends Parser { return { info, name }; } - /** @typedef {{ type: "call", call: CallExpressionNode, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => string[], name: string, getMembers: () => string[]}} CallExpressionInfo */ - /** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => string[]}} ExpressionExpressionInfo */ + /** @typedef {{ type: "call", call: CallExpressionNode, calleeName: string, rootInfo: string | VariableInfo, getCalleeMembers: () => string[], name: string, getMembers: () => string[], getMembersOptionals: () => boolean[]}} CallExpressionInfo */ + /** @typedef {{ type: "expression", rootInfo: string | VariableInfo, name: string, getMembers: () => string[], getMembersOptionals: () => boolean[]}} ExpressionExpressionInfo */ /** * @param {MemberExpressionNode} expression a member expression @@ -3658,7 +3673,8 @@ class JavascriptParser extends Parser { * @returns {CallExpressionInfo | ExpressionExpressionInfo | undefined} expression info */ getMemberExpressionInfo(expression, allowedTypes) { - const { object, members } = this.extractMemberExpressionChain(expression); + const { object, members, membersOptionals } = + this.extractMemberExpressionChain(expression); switch (object.type) { case "CallExpression": { if ((allowedTypes & ALLOWED_MEMBER_TYPES_CALL_EXPRESSION) === 0) @@ -3682,7 +3698,8 @@ class JavascriptParser extends Parser { rootInfo, getCalleeMembers: memoize(() => rootMembers.reverse()), name: objectAndMembersToName(`${calleeName}()`, members), - getMembers: memoize(() => members.reverse()) + getMembers: memoize(() => members.reverse()), + getMembersOptionals: memoize(() => membersOptionals.reverse()) }; } case "Identifier": @@ -3700,7 +3717,8 @@ class JavascriptParser extends Parser { type: "expression", name: objectAndMembersToName(resolvedRoot, members), rootInfo, - getMembers: memoize(() => members.reverse()) + getMembers: memoize(() => members.reverse()), + getMembersOptionals: memoize(() => membersOptionals.reverse()) }; } } diff --git a/lib/runtime/BaseUriRuntimeModule.js b/lib/runtime/BaseUriRuntimeModule.js new file mode 100644 index 000000000..bbc719c33 --- /dev/null +++ b/lib/runtime/BaseUriRuntimeModule.js @@ -0,0 +1,31 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const RuntimeGlobals = require("../RuntimeGlobals"); +const RuntimeModule = require("../RuntimeModule"); + +class BaseUriRuntimeModule extends RuntimeModule { + constructor() { + super("base uri", RuntimeModule.STAGE_ATTACH); + } + + /** + * @returns {string} runtime code + */ + generate() { + const { chunk } = this; + + const options = chunk.getEntryOptions(); + return `${RuntimeGlobals.baseURI} = ${ + options.baseUri === undefined + ? "undefined" + : JSON.stringify(options.baseUri) + };`; + } +} + +module.exports = BaseUriRuntimeModule; diff --git a/lib/stats/DefaultStatsFactoryPlugin.js b/lib/stats/DefaultStatsFactoryPlugin.js index b99ce1708..57e52703a 100644 --- a/lib/stats/DefaultStatsFactoryPlugin.js +++ b/lib/stats/DefaultStatsFactoryPlugin.js @@ -2155,7 +2155,7 @@ const RESULT_GROUPERS = { // remove a prefixed "!" that can be specified to reverse sort order const normalizeFieldKey = field => { if (field[0] === "!") { - return field.substr(1); + return field.slice(1); } return field; }; diff --git a/test/Defaults.unittest.js b/test/Defaults.unittest.js index 13c87da9f..b9fee53b7 100644 --- a/test/Defaults.unittest.js +++ b/test/Defaults.unittest.js @@ -1060,6 +1060,197 @@ describe("snapshots", () => { + "uniqueName": "myLib.awesome", `) ); + test( + "library contains [name] placeholder", + { + output: { + library: ["myLib", "[name]"] + } + }, + e => + e.toMatchInlineSnapshot(` + - Expected + + Received + + @@ ... @@ + - "chunkLoadingGlobal": "webpackChunkwebpack", + + "chunkLoadingGlobal": "webpackChunkmyLib", + @@ ... @@ + - "devtoolNamespace": "webpack", + + "devtoolNamespace": "myLib", + @@ ... @@ + - "enabledLibraryTypes": Array [], + + "enabledLibraryTypes": Array [ + + "var", + + ], + @@ ... @@ + - "hotUpdateGlobal": "webpackHotUpdatewebpack", + + "hotUpdateGlobal": "webpackHotUpdatemyLib", + @@ ... @@ + - "library": undefined, + + "library": Object { + + "auxiliaryComment": undefined, + + "export": undefined, + + "name": Array [ + + "myLib", + + "[name]", + + ], + + "type": "var", + + "umdNamedDefine": undefined, + + }, + @@ ... @@ + - "uniqueName": "webpack", + + "uniqueName": "myLib", + `) + ); + test( + "library.name contains [name] placeholder", + { + output: { + library: { + name: ["my[name]Lib", "[name]", "lib"], + type: "var" + } + } + }, + e => + e.toMatchInlineSnapshot(` + - Expected + + Received + + @@ ... @@ + - "chunkLoadingGlobal": "webpackChunkwebpack", + + "chunkLoadingGlobal": "webpackChunkmyLib_lib", + @@ ... @@ + - "devtoolNamespace": "webpack", + + "devtoolNamespace": "myLib.lib", + @@ ... @@ + - "enabledLibraryTypes": Array [], + + "enabledLibraryTypes": Array [ + + "var", + + ], + @@ ... @@ + - "hotUpdateGlobal": "webpackHotUpdatewebpack", + + "hotUpdateGlobal": "webpackHotUpdatemyLib_lib", + @@ ... @@ + - "library": undefined, + + "library": Object { + + "auxiliaryComment": undefined, + + "export": undefined, + + "name": Array [ + + "my[name]Lib", + + "[name]", + + "lib", + + ], + + "type": "var", + + "umdNamedDefine": undefined, + + }, + @@ ... @@ + - "uniqueName": "webpack", + + "uniqueName": "myLib.lib", + `) + ); + test( + "library.name.root contains [name] placeholder", + { + output: { + library: { + name: { + root: ["[name]", "myLib"] + }, + type: "var" + } + } + }, + e => + e.toMatchInlineSnapshot(` + - Expected + + Received + + @@ ... @@ + - "chunkLoadingGlobal": "webpackChunkwebpack", + + "chunkLoadingGlobal": "webpackChunkmyLib", + @@ ... @@ + - "devtoolNamespace": "webpack", + + "devtoolNamespace": "myLib", + @@ ... @@ + - "enabledLibraryTypes": Array [], + + "enabledLibraryTypes": Array [ + + "var", + + ], + @@ ... @@ + - "hotUpdateGlobal": "webpackHotUpdatewebpack", + + "hotUpdateGlobal": "webpackHotUpdatemyLib", + @@ ... @@ + - "library": undefined, + + "library": Object { + + "auxiliaryComment": undefined, + + "export": undefined, + + "name": Object { + + "root": Array [ + + "[name]", + + "myLib", + + ], + + }, + + "type": "var", + + "umdNamedDefine": undefined, + + }, + @@ ... @@ + - "uniqueName": "webpack", + + "uniqueName": "myLib", + `) + ); + test( + "library.name.root contains escaped placeholder", + { + output: { + library: { + name: { + root: ["[\\name\\]", "my[\\name\\]Lib[name]", "[\\name\\]"] + }, + type: "var" + } + } + }, + e => + e.toMatchInlineSnapshot(` + - Expected + + Received + + @@ ... @@ + - "chunkLoadingGlobal": "webpackChunkwebpack", + + "chunkLoadingGlobal": "webpackChunk_name_my_name_Lib_name_", + @@ ... @@ + - "devtoolNamespace": "webpack", + + "devtoolNamespace": "[name].my[name]Lib.[name]", + @@ ... @@ + - "enabledLibraryTypes": Array [], + + "enabledLibraryTypes": Array [ + + "var", + + ], + @@ ... @@ + - "hotUpdateGlobal": "webpackHotUpdatewebpack", + + "hotUpdateGlobal": "webpackHotUpdate_name_my_name_Lib_name_", + @@ ... @@ + - "library": undefined, + + "library": Object { + + "auxiliaryComment": undefined, + + "export": undefined, + + "name": Object { + + "root": Array [ + + "[\\\\name\\\\]", + + "my[\\\\name\\\\]Lib[name]", + + "[\\\\name\\\\]", + + ], + + }, + + "type": "var", + + "umdNamedDefine": undefined, + + }, + @@ ... @@ + - "uniqueName": "webpack", + + "uniqueName": "[name].my[name]Lib.[name]", + `) + ); test("target node", { target: "node" }, e => e.toMatchInlineSnapshot(` - Expected diff --git a/test/Examples.test.js b/test/Examples.test.js index 39a39608a..15821007c 100644 --- a/test/Examples.test.js +++ b/test/Examples.test.js @@ -22,8 +22,8 @@ describe("Examples", () => { let options = {}; let webpackConfigPath = path.join(examplePath, "webpack.config.js"); webpackConfigPath = - webpackConfigPath.substr(0, 1).toUpperCase() + - webpackConfigPath.substr(1); + webpackConfigPath.slice(0, 1).toUpperCase() + + webpackConfigPath.slice(1); if (fs.existsSync(webpackConfigPath)) options = require(webpackConfigPath); if (typeof options === "function") options = options(); diff --git a/test/HotTestCases.template.js b/test/HotTestCases.template.js index 8c086f5fd..ccf95706b 100644 --- a/test/HotTestCases.template.js +++ b/test/HotTestCases.template.js @@ -249,7 +249,7 @@ const describeCases = config => { } function _require(module) { - if (module.substr(0, 2) === "./") { + if (module.startsWith("./")) { const p = path.join(outputDirectory, module); if (module.endsWith(".json")) { return JSON.parse(fs.readFileSync(p, "utf-8")); diff --git a/test/JavascriptParser.unittest.js b/test/JavascriptParser.unittest.js index 813f07fc6..0e7ebd94b 100644 --- a/test/JavascriptParser.unittest.js +++ b/test/JavascriptParser.unittest.js @@ -256,7 +256,7 @@ describe("JavascriptParser", () => { Object.keys(testCases).forEach(name => { it("should parse " + name, () => { let source = testCases[name][0].toString(); - source = source.substr(13, source.length - 14).trim(); + source = source.slice(13, -1).trim(); const state = testCases[name][1]; const testParser = new JavascriptParser({}); @@ -541,12 +541,12 @@ describe("JavascriptParser", () => { "`start${'str'}mid${obj2}end`": // eslint-disable-next-line no-template-curly-in-string "template=[start${'str'}mid string=startstrmid],[end string=end]", - "'abc'.substr(1)": "string=bc", - "'abcdef'.substr(2, 3)": "string=cde", + "'abc'.slice(1)": "string=bc", + "'abcdef'.slice(2, 5)": "string=cde", "'abcdef'.substring(2, 3)": "string=c", "'abcdef'.substring(2, 3, 4)": "", - "'abc'[\"substr\"](1)": "string=bc", - "'abc'[substr](1)": "", + "'abc'[\"slice\"](1)": "string=bc", + "'abc'[slice](1)": "", "'1,2+3'.split(/[,+]/)": "array=[1],[2],[3]", "'1,2+3'.split(expr)": "", "'a' + (expr + 'c')": "wrapped=['a' string=a]+['c' string=c]", @@ -596,7 +596,7 @@ describe("JavascriptParser", () => { const start = evalExpr.range[0] - 5; const end = evalExpr.range[1] - 5; return ( - key.substr(start, end - start) + + key.slice(start, end) + (result.length > 0 ? " " + result.join(" ") : "") ); } diff --git a/test/TestCases.template.js b/test/TestCases.template.js index 909b3989f..43619be9b 100644 --- a/test/TestCases.template.js +++ b/test/TestCases.template.js @@ -427,7 +427,7 @@ const describeCases = config => { }); cleanups.push(() => (esmContext.it = undefined)); function _require(module, esmMode) { - if (module.substr(0, 2) === "./") { + if (module.startsWith("./")) { const p = path.join(outputDirectory, module); const content = fs.readFileSync(p, "utf-8"); if (p.endsWith(".mjs")) { diff --git a/test/benchmarkCases/many-chunks/b.js b/test/benchmarkCases/many-chunks/b.js index 670c28f0d..3d3fd298e 100644 --- a/test/benchmarkCases/many-chunks/b.js +++ b/test/benchmarkCases/many-chunks/b.js @@ -3,4 +3,4 @@ import("./c?1" + __resourceQuery); import("./c?2" + __resourceQuery); import("./c?3" + __resourceQuery); import("./c?4" + __resourceQuery); -import("./a" + __resourceQuery.substr(0, 2)); +import("./a" + __resourceQuery.slice(0, 2)); diff --git a/test/benchmarkCases/many-modules-source-map/b.js b/test/benchmarkCases/many-modules-source-map/b.js index 269a25723..d0d91d3f7 100644 --- a/test/benchmarkCases/many-modules-source-map/b.js +++ b/test/benchmarkCases/many-modules-source-map/b.js @@ -8,4 +8,4 @@ require("./c?6" + __resourceQuery); require("./c?7" + __resourceQuery); require("./c?8" + __resourceQuery); require("./c?9" + __resourceQuery); -require("./a" + __resourceQuery.substr(0, 2)); +require("./a" + __resourceQuery.slice(0, 2)); diff --git a/test/benchmarkCases/many-modules/b.js b/test/benchmarkCases/many-modules/b.js index 269a25723..d0d91d3f7 100644 --- a/test/benchmarkCases/many-modules/b.js +++ b/test/benchmarkCases/many-modules/b.js @@ -8,4 +8,4 @@ require("./c?6" + __resourceQuery); require("./c?7" + __resourceQuery); require("./c?8" + __resourceQuery); require("./c?9" + __resourceQuery); -require("./a" + __resourceQuery.substr(0, 2)); +require("./a" + __resourceQuery.slice(0, 2)); diff --git a/test/benchmarkCases/many-stuff-harmony/a.js b/test/benchmarkCases/many-stuff-harmony/a.js index be76a2187..30dd82bc0 100644 --- a/test/benchmarkCases/many-stuff-harmony/a.js +++ b/test/benchmarkCases/many-stuff-harmony/a.js @@ -1,7 +1,7 @@ module.exports = function() { let str = ""; let sum = ["1"]; - const query = +this.query.substr(1); + const query = +this.query.slice(1); for(let i = 0; i < query; i++) { str += `import b${i} from "./b?${Math.floor(i/2)}!";\n`; sum.push(`b${i}`); diff --git a/test/cases/compile/long-module-chain/module.js b/test/cases/compile/long-module-chain/module.js index 30bf15c0c..10eccfc47 100644 --- a/test/cases/compile/long-module-chain/module.js +++ b/test/cases/compile/long-module-chain/module.js @@ -1,5 +1,5 @@ if(__resourceQuery === "?0") { module.exports = "module"; } else { - module.exports = require("./module?" + (+__resourceQuery.substr(1) - 1)); + module.exports = require("./module?" + (+__resourceQuery.slice(1) - 1)); } diff --git a/test/cases/errors/loader-error-warning/error-loader.js b/test/cases/errors/loader-error-warning/error-loader.js index 8c63082d4..981790bb5 100644 --- a/test/cases/errors/loader-error-warning/error-loader.js +++ b/test/cases/errors/loader-error-warning/error-loader.js @@ -1,6 +1,6 @@ /** @type {import("../../../../").LoaderDefinition} */ module.exports = function (source) { //@ts-expect-error errors must be Errors, string is not recommended and should lead to type error - this.emitError(this.query.substr(1)); + this.emitError(this.query.slice(1)); return source; }; diff --git a/test/cases/errors/loader-error-warning/warning-loader.js b/test/cases/errors/loader-error-warning/warning-loader.js index adc1a120a..90c6ad19d 100644 --- a/test/cases/errors/loader-error-warning/warning-loader.js +++ b/test/cases/errors/loader-error-warning/warning-loader.js @@ -1,6 +1,6 @@ /** @type {import("../../../../").LoaderDefinition} */ module.exports = function (source) { //@ts-expect-error warnings must be Errors, string is not recommended and should lead to type error - this.emitWarning(this.query.substr(1)); + this.emitWarning(this.query.slice(1)); return source; }; diff --git a/test/cases/loaders/import-module/a.json b/test/cases/loaders/import-module/a.json new file mode 100644 index 000000000..0187f3b09 --- /dev/null +++ b/test/cases/loaders/import-module/a.json @@ -0,0 +1 @@ +{"a":1} diff --git a/test/cases/loaders/import-module/index.js b/test/cases/loaders/import-module/index.js new file mode 100644 index 000000000..56a4d03f1 --- /dev/null +++ b/test/cases/loaders/import-module/index.js @@ -0,0 +1,6 @@ +import content from "./loader!!"; + +it("should compile", () => { + expect(typeof content).toBe("string"); + expect(content.startsWith("webpack://")).toBe(true); +}); diff --git a/test/cases/loaders/import-module/loader.js b/test/cases/loaders/import-module/loader.js new file mode 100644 index 000000000..960d39ff9 --- /dev/null +++ b/test/cases/loaders/import-module/loader.js @@ -0,0 +1,25 @@ +"use strict"; + +const path = require("path"); + +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { + const callback = this.async(); + this.importModule( + path.resolve(__dirname, "module.js"), + { baseUri: "webpack://" }, + (error, exports) => { + if (error) { + callback(error); + return; + } + + callback( + null, + `module.exports = ${ + exports.asset ? JSON.stringify(exports.asset) : undefined + }` + ); + } + ); +}; diff --git a/test/cases/loaders/import-module/module.js b/test/cases/loaders/import-module/module.js new file mode 100644 index 000000000..97520ef46 --- /dev/null +++ b/test/cases/loaders/import-module/module.js @@ -0,0 +1,3 @@ +const asset = new URL("./a.json", import.meta.url); + +export { asset } diff --git a/test/cases/loaders/import-module/test.filter.js b/test/cases/loaders/import-module/test.filter.js new file mode 100644 index 000000000..a65d1ab49 --- /dev/null +++ b/test/cases/loaders/import-module/test.filter.js @@ -0,0 +1,3 @@ +module.exports = config => { + return !config.module; +}; diff --git a/test/cases/parsing/evaluate/resourceFragment/index.js b/test/cases/parsing/evaluate/resourceFragment/index.js index fc699a5aa..cf443cdc4 100644 --- a/test/cases/parsing/evaluate/resourceFragment/index.js +++ b/test/cases/parsing/evaluate/resourceFragment/index.js @@ -1,3 +1,3 @@ module.exports = require(( - __resourceFragment.substr(1) + "/resourceFragment/returnRF#XXXFragment" + __resourceFragment.slice(1) + "/resourceFragment/returnRF#XXXFragment" ).replace(/XXX/g, "resource")); diff --git a/test/cases/parsing/evaluate/resourceQuery/index.js b/test/cases/parsing/evaluate/resourceQuery/index.js index 21596f973..173f9da8d 100644 --- a/test/cases/parsing/evaluate/resourceQuery/index.js +++ b/test/cases/parsing/evaluate/resourceQuery/index.js @@ -1 +1 @@ -module.exports = require((__resourceQuery.substr(1) + "/resourceQuery/returnRQ?XXXQuery").replace(/XXX/g, "resource")); \ No newline at end of file +module.exports = require((__resourceQuery.slice(1) + "/resourceQuery/returnRQ?XXXQuery").replace(/XXX/g, "resource")); diff --git a/test/cases/parsing/extract-amd.nominimize/index.js b/test/cases/parsing/extract-amd.nominimize/index.js index a79383e00..3bfc3fa27 100644 --- a/test/cases/parsing/extract-amd.nominimize/index.js +++ b/test/cases/parsing/extract-amd.nominimize/index.js @@ -17,7 +17,7 @@ it("should parse fancy function calls with arrow functions", function() { it("should parse fancy AMD calls with arrow functions", function() { require("./constructor ./a".split(" ")); - require("-> module module exports *constructor *a".replace("module", "require").substr(3).replace(/\*/g, "./").split(" "), (require, module, exports, constructor, a) => { + require("-> module module exports *constructor *a".replace("module", "require").slice(3).replace(/\*/g, "./").split(" "), (require, module, exports, constructor, a) => { expect((typeof require)).toBe("function"); expect((typeof module)).toBe("object"); expect((typeof exports)).toBe("object"); @@ -25,7 +25,7 @@ it("should parse fancy AMD calls with arrow functions", function() { expect((typeof constructor)).toBe("function"); expect(a).toBe("a"); }); - define("-> module module exports *constructor *a".replace("module", "require").substr(3).replace(/\*/g, "./").split(" "), (require, module, exports, constructor, a) => { + define("-> module module exports *constructor *a".replace("module", "require").slice(3).replace(/\*/g, "./").split(" "), (require, module, exports, constructor, a) => { expect((typeof require)).toBe("function"); expect((typeof module)).toBe("object"); expect((typeof exports)).toBe("object"); diff --git a/test/cases/parsing/extract-amd/index.js b/test/cases/parsing/extract-amd/index.js index 13cc0d3f0..39822b5b9 100644 --- a/test/cases/parsing/extract-amd/index.js +++ b/test/cases/parsing/extract-amd/index.js @@ -17,7 +17,7 @@ it("should parse fancy function calls", function() { it("should parse fancy AMD calls", function() { require("./constructor ./a".split(" ")); - require("-> module module exports *constructor *a".replace("module", "require").substr(3).replace(/\*/g, "./").split(" "), function(require, module, exports, constructor, a) { + require("-> module module exports *constructor *a".replace("module", "require").slice(3).replace(/\*/g, "./").split(" "), function(require, module, exports, constructor, a) { expect((typeof require)).toBe("function"); expect((typeof module)).toBe("object"); expect((typeof exports)).toBe("object"); @@ -25,7 +25,7 @@ it("should parse fancy AMD calls", function() { expect((typeof constructor)).toBe("function"); expect(a).toBe("a"); }); - define("-> module module exports *constructor *a".replace("module", "require").substr(3).replace(/\*/g, "./").split(" "), function(require, module, exports, constructor, a) { + define("-> module module exports *constructor *a".replace("module", "require").slice(3).replace(/\*/g, "./").split(" "), function(require, module, exports, constructor, a) { expect((typeof require)).toBe("function"); expect((typeof module)).toBe("object"); expect((typeof exports)).toBe("object"); diff --git a/test/cases/parsing/optional-chaining/b.js b/test/cases/parsing/optional-chaining/b.js new file mode 100644 index 000000000..5fe49d553 --- /dev/null +++ b/test/cases/parsing/optional-chaining/b.js @@ -0,0 +1,3 @@ +export default {}; +export * as a from "./c"; +export const call = () => ({ c: 1 }); diff --git a/test/cases/parsing/optional-chaining/c.js b/test/cases/parsing/optional-chaining/c.js new file mode 100644 index 000000000..c37f7387e --- /dev/null +++ b/test/cases/parsing/optional-chaining/c.js @@ -0,0 +1,2 @@ +const call = () => 2; +export { call }; diff --git a/test/cases/parsing/optional-chaining/index.js b/test/cases/parsing/optional-chaining/index.js index cff0a3dbb..0d48ae94d 100644 --- a/test/cases/parsing/optional-chaining/index.js +++ b/test/cases/parsing/optional-chaining/index.js @@ -1,3 +1,15 @@ +import b, * as bb from "./b"; + +it("should keep optional chaining", () => { + expect(b?.a?.a).toBe(undefined); + expect(b?.a).toBe(undefined); + expect(typeof bb?.a).toBe("object"); + expect(bb.call?.().c).toBe(1); + expect(bb.call?.().b?.a).toBe(undefined); + expect(bb.a?.call()).toBe(2); + expect(bb.a?.c?.b).toBe(undefined); +}); + it("should evaluate optional members", () => { if (!module.hot) { expect( diff --git a/test/helpers/FakeDocument.js b/test/helpers/FakeDocument.js index aa837df29..c87ccce77 100644 --- a/test/helpers/FakeDocument.js +++ b/test/helpers/FakeDocument.js @@ -104,9 +104,9 @@ class FakeElement { if (/^\//.test(value)) { return `https://test.cases${value}`; } else if (/^\.\.\//.test(value)) { - return `https://test.cases${value.substr(2)}`; + return `https://test.cases${value.slice(2)}`; } else if (/^\.\//.test(value)) { - return `https://test.cases/path${value.substr(1)}`; + return `https://test.cases/path${value.slice(1)}`; } else if (/^\w+:\/\//.test(value)) { return value; } else if (/^\/\//.test(value)) { diff --git a/types.d.ts b/types.d.ts index 7ab6cc78b..477dbba75 100644 --- a/types.d.ts +++ b/types.d.ts @@ -477,6 +477,7 @@ declare abstract class BasicEvaluatedExpression { identifier?: string; rootInfo: VariableInfoInterface; getMembers: () => string[]; + getMembersOptionals: () => boolean[]; expression: NodeEstreeIndex; isUnknown(): boolean; isNull(): boolean; @@ -528,7 +529,8 @@ declare abstract class BasicEvaluatedExpression { setIdentifier( identifier?: any, rootInfo?: any, - getMembers?: any + getMembers?: any, + getMembersOptionals?: any ): BasicEvaluatedExpression; setWrapped( prefix?: any, @@ -681,6 +683,7 @@ declare interface CallExpressionInfo { getCalleeMembers: () => string[]; name: string; getMembers: () => string[]; + getMembersOptionals: () => boolean[]; } declare interface CallbackAsyncQueue { (err?: null | WebpackError, result?: T): any; @@ -3824,6 +3827,7 @@ declare interface ExpressionExpressionInfo { rootInfo: string | VariableInfo; name: string; getMembers: () => string[]; + getMembersOptionals: () => boolean[]; } type ExternalItem = | string @@ -5102,7 +5106,7 @@ declare class JavascriptParser extends Parser { topLevelAwait: SyncBailHook<[Expression], boolean | void>; call: HookMap>; callMemberChain: HookMap< - SyncBailHook<[CallExpression, string[]], boolean | void> + SyncBailHook<[CallExpression, string[], boolean[]], boolean | void> >; memberChainOfCallMemberChain: HookMap< SyncBailHook< @@ -5120,7 +5124,7 @@ declare class JavascriptParser extends Parser { new: HookMap>; expression: HookMap>; expressionMemberChain: HookMap< - SyncBailHook<[Expression, string[]], boolean | void> + SyncBailHook<[Expression, string[], boolean[]], boolean | void> >; unhandledExpressionMemberChain: HookMap< SyncBailHook<[Expression, string[]], boolean | void> @@ -5335,12 +5339,10 @@ declare class JavascriptParser extends Parser { enterArrayPattern(pattern?: any, onIdent?: any): void; enterRestElement(pattern?: any, onIdent?: any): void; enterAssignmentPattern(pattern?: any, onIdent?: any): void; - evaluateExpression( - expression: Expression - ): undefined | BasicEvaluatedExpression; + evaluateExpression(expression: Expression): BasicEvaluatedExpression; parseString(expression?: any): any; parseCalculatedString(expression?: any): any; - evaluate(source?: any): undefined | BasicEvaluatedExpression; + evaluate(source: string): BasicEvaluatedExpression; isPure( expr: | undefined @@ -5423,6 +5425,7 @@ declare class JavascriptParser extends Parser { | ImportExpression | ChainExpression | Super; + membersOptionals: boolean[]; }; getFreeInfoFromVariable(varName: string): { name: string; @@ -7486,11 +7489,11 @@ type NodeEstreeIndex = | PropertyDefinition | VariableDeclarator | Program - | Super | SwitchCase | CatchClause | Property | AssignmentProperty + | Super | TemplateElement | SpreadElement | ObjectPattern