webpack 5.98.0 → 5.99.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (251) hide show
  1. package/README.md +7 -3
  2. package/lib/AsyncDependenciesBlock.js +3 -1
  3. package/lib/BannerPlugin.js +1 -1
  4. package/lib/Cache.js +9 -7
  5. package/lib/CacheFacade.js +5 -5
  6. package/lib/Chunk.js +2 -2
  7. package/lib/ChunkGraph.js +21 -16
  8. package/lib/ChunkTemplate.js +6 -6
  9. package/lib/CleanPlugin.js +10 -10
  10. package/lib/CodeGenerationResults.js +4 -3
  11. package/lib/CompatibilityPlugin.js +4 -1
  12. package/lib/Compilation.js +326 -152
  13. package/lib/Compiler.js +13 -18
  14. package/lib/ConditionalInitFragment.js +1 -1
  15. package/lib/ConstPlugin.js +5 -3
  16. package/lib/ContextModule.js +4 -2
  17. package/lib/ContextModuleFactory.js +3 -3
  18. package/lib/ContextReplacementPlugin.js +43 -16
  19. package/lib/DefinePlugin.js +25 -24
  20. package/lib/DelegatedModule.js +4 -2
  21. package/lib/DelegatedModuleFactoryPlugin.js +2 -1
  22. package/lib/Dependency.js +19 -13
  23. package/lib/DependencyTemplates.js +4 -3
  24. package/lib/DllModule.js +4 -2
  25. package/lib/DllModuleFactory.js +2 -2
  26. package/lib/DllReferencePlugin.js +2 -1
  27. package/lib/DynamicEntryPlugin.js +1 -1
  28. package/lib/EnvironmentPlugin.js +4 -2
  29. package/lib/ExportsInfo.js +72 -40
  30. package/lib/ExternalModule.js +14 -5
  31. package/lib/ExternalModuleFactoryPlugin.js +24 -12
  32. package/lib/FileSystemInfo.js +129 -94
  33. package/lib/FlagDependencyExportsPlugin.js +6 -4
  34. package/lib/FlagDependencyUsagePlugin.js +1 -1
  35. package/lib/Generator.js +29 -1
  36. package/lib/HookWebpackError.js +2 -2
  37. package/lib/HotModuleReplacementPlugin.js +3 -9
  38. package/lib/IgnoreErrorModuleFactory.js +2 -2
  39. package/lib/IgnorePlugin.js +0 -5
  40. package/lib/InitFragment.js +1 -1
  41. package/lib/LoaderOptionsPlugin.js +8 -5
  42. package/lib/MainTemplate.js +7 -7
  43. package/lib/Module.js +40 -17
  44. package/lib/ModuleBuildError.js +3 -1
  45. package/lib/ModuleDependencyError.js +4 -3
  46. package/lib/ModuleDependencyWarning.js +4 -3
  47. package/lib/ModuleFactory.js +9 -3
  48. package/lib/ModuleFilenameHelpers.js +13 -13
  49. package/lib/ModuleGraph.js +20 -14
  50. package/lib/ModuleGraphConnection.js +7 -13
  51. package/lib/ModuleNotFoundError.js +1 -1
  52. package/lib/ModuleParseError.js +2 -1
  53. package/lib/ModuleSourceTypesConstants.js +11 -0
  54. package/lib/ModuleTemplate.js +5 -5
  55. package/lib/ModuleTypeConstants.js +15 -0
  56. package/lib/MultiCompiler.js +4 -4
  57. package/lib/MultiStats.js +1 -1
  58. package/lib/NormalModule.js +101 -54
  59. package/lib/NormalModuleFactory.js +38 -33
  60. package/lib/NormalModuleReplacementPlugin.js +3 -2
  61. package/lib/NullFactory.js +2 -2
  62. package/lib/Parser.js +4 -3
  63. package/lib/ProgressPlugin.js +1 -2
  64. package/lib/RawModule.js +4 -2
  65. package/lib/RecordIdsPlugin.js +6 -2
  66. package/lib/RequestShortener.js +3 -1
  67. package/lib/ResolverFactory.js +12 -9
  68. package/lib/RuntimeModule.js +4 -2
  69. package/lib/RuntimeTemplate.js +2 -1
  70. package/lib/SelfModuleFactory.js +2 -2
  71. package/lib/SourceMapDevToolPlugin.js +0 -8
  72. package/lib/Template.js +6 -5
  73. package/lib/TemplatedPathPlugin.js +15 -12
  74. package/lib/WebpackOptionsApply.js +1 -1
  75. package/lib/asset/AssetGenerator.js +237 -170
  76. package/lib/asset/AssetModulesPlugin.js +50 -8
  77. package/lib/asset/AssetSourceGenerator.js +18 -0
  78. package/lib/asset/RawDataUrlModule.js +4 -2
  79. package/lib/buildChunkGraph.js +14 -4
  80. package/lib/cache/MemoryWithGcCachePlugin.js +6 -2
  81. package/lib/cache/PackFileCacheStrategy.js +137 -121
  82. package/lib/cache/ResolverCachePlugin.js +15 -7
  83. package/lib/cache/getLazyHashedEtag.js +4 -3
  84. package/lib/cli.js +23 -15
  85. package/lib/config/defaults.js +93 -26
  86. package/lib/config/normalization.js +14 -13
  87. package/lib/config/target.js +8 -8
  88. package/lib/container/ContainerEntryModule.js +4 -2
  89. package/lib/container/ContainerEntryModuleFactory.js +2 -2
  90. package/lib/container/FallbackModule.js +4 -2
  91. package/lib/container/FallbackModuleFactory.js +2 -2
  92. package/lib/container/RemoteModule.js +4 -2
  93. package/lib/container/options.js +5 -5
  94. package/lib/css/CssGenerator.js +71 -9
  95. package/lib/css/CssModulesPlugin.js +30 -5
  96. package/lib/css/CssParser.js +37 -17
  97. package/lib/css/walkCssTokens.js +17 -17
  98. package/lib/debug/ProfilingPlugin.js +98 -38
  99. package/lib/dependencies/AMDDefineDependencyParserPlugin.js +10 -4
  100. package/lib/dependencies/AMDPlugin.js +5 -2
  101. package/lib/dependencies/AMDRequireArrayDependency.js +4 -3
  102. package/lib/dependencies/AMDRequireContextDependency.js +2 -1
  103. package/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js +15 -7
  104. package/lib/dependencies/AMDRuntimeModules.js +3 -1
  105. package/lib/dependencies/CommonJsExportRequireDependency.js +4 -5
  106. package/lib/dependencies/CommonJsExportsParserPlugin.js +3 -3
  107. package/lib/dependencies/CommonJsImportsParserPlugin.js +8 -7
  108. package/lib/dependencies/CommonJsRequireContextDependency.js +2 -1
  109. package/lib/dependencies/ContextDependencyHelpers.js +13 -6
  110. package/lib/dependencies/CssIcssExportDependency.js +15 -12
  111. package/lib/dependencies/CssIcssImportDependency.js +4 -1
  112. package/lib/dependencies/CssLocalIdentifierDependency.js +17 -14
  113. package/lib/dependencies/ExportsInfoDependency.js +6 -1
  114. package/lib/dependencies/HarmonyEvaluatedImportSpecifierDependency.js +5 -5
  115. package/lib/dependencies/HarmonyExportDependencyParserPlugin.js +22 -15
  116. package/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +23 -8
  117. package/lib/dependencies/HarmonyExportSpecifierDependency.js +2 -2
  118. package/lib/dependencies/HarmonyImportDependency.js +8 -6
  119. package/lib/dependencies/HarmonyImportDependencyParserPlugin.js +19 -14
  120. package/lib/dependencies/HarmonyImportSpecifierDependency.js +5 -5
  121. package/lib/dependencies/ImportContextDependency.js +2 -1
  122. package/lib/dependencies/ImportMetaContextDependencyParserPlugin.js +8 -4
  123. package/lib/dependencies/JsonExportsDependency.js +24 -8
  124. package/lib/dependencies/LoaderPlugin.js +4 -14
  125. package/lib/dependencies/RequireContextDependency.js +2 -1
  126. package/lib/dependencies/RequireContextDependencyParserPlugin.js +6 -3
  127. package/lib/dependencies/RequireEnsureDependenciesBlock.js +3 -2
  128. package/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js +11 -5
  129. package/lib/dependencies/RequireResolveContextDependency.js +1 -1
  130. package/lib/dependencies/WebAssemblyExportImportedDependency.js +1 -1
  131. package/lib/dependencies/WorkerDependency.js +6 -3
  132. package/lib/dependencies/WorkerPlugin.js +100 -41
  133. package/lib/esm/ModuleChunkFormatPlugin.js +5 -0
  134. package/lib/hmr/HotModuleReplacement.runtime.js +1 -0
  135. package/lib/hmr/JavascriptHotModuleReplacement.runtime.js +1 -0
  136. package/lib/hmr/LazyCompilationPlugin.js +32 -24
  137. package/lib/hmr/lazyCompilationBackend.js +1 -1
  138. package/lib/ids/DeterministicModuleIdsPlugin.js +1 -1
  139. package/lib/ids/HashedModuleIdsPlugin.js +2 -1
  140. package/lib/ids/IdHelpers.js +15 -14
  141. package/lib/ids/SyncModuleIdsPlugin.js +9 -5
  142. package/lib/index.js +5 -5
  143. package/lib/javascript/BasicEvaluatedExpression.js +6 -6
  144. package/lib/javascript/JavascriptGenerator.js +11 -1
  145. package/lib/javascript/JavascriptModulesPlugin.js +51 -31
  146. package/lib/javascript/JavascriptParser.js +287 -188
  147. package/lib/javascript/JavascriptParserHelpers.js +10 -9
  148. package/lib/javascript/StartupHelpers.js +4 -1
  149. package/lib/json/JsonData.js +4 -4
  150. package/lib/json/JsonGenerator.js +54 -22
  151. package/lib/json/JsonModulesPlugin.js +16 -2
  152. package/lib/json/JsonParser.js +8 -4
  153. package/lib/library/AbstractLibraryPlugin.js +7 -3
  154. package/lib/library/AssignLibraryPlugin.js +29 -1
  155. package/lib/library/EnableLibraryPlugin.js +7 -10
  156. package/lib/library/ExportPropertyLibraryPlugin.js +4 -1
  157. package/lib/library/ModuleLibraryPlugin.js +121 -15
  158. package/lib/logging/Logger.js +2 -2
  159. package/lib/logging/createConsoleLogger.js +4 -4
  160. package/lib/node/NodeEnvironmentPlugin.js +6 -2
  161. package/lib/node/ReadFileCompileAsyncWasmPlugin.js +1 -2
  162. package/lib/node/ReadFileCompileWasmPlugin.js +1 -2
  163. package/lib/node/nodeConsole.js +3 -1
  164. package/lib/optimize/AggressiveSplittingPlugin.js +1 -1
  165. package/lib/optimize/ConcatenatedModule.js +19 -12
  166. package/lib/optimize/InnerGraph.js +3 -2
  167. package/lib/optimize/InnerGraphPlugin.js +13 -7
  168. package/lib/optimize/LimitChunkCountPlugin.js +20 -0
  169. package/lib/optimize/ModuleConcatenationPlugin.js +10 -7
  170. package/lib/optimize/RealContentHashPlugin.js +8 -4
  171. package/lib/optimize/SideEffectsFlagPlugin.js +4 -2
  172. package/lib/optimize/SplitChunksPlugin.js +87 -65
  173. package/lib/rules/BasicEffectRulePlugin.js +9 -1
  174. package/lib/rules/BasicMatcherRulePlugin.js +15 -4
  175. package/lib/rules/ObjectMatcherRulePlugin.js +12 -3
  176. package/lib/rules/RuleSetCompiler.js +25 -14
  177. package/lib/rules/UseEffectRulePlugin.js +47 -17
  178. package/lib/runtime/GetChunkFilenameRuntimeModule.js +6 -6
  179. package/lib/schemes/HttpUriPlugin.js +38 -17
  180. package/lib/serialization/BinaryMiddleware.js +52 -19
  181. package/lib/serialization/FileMiddleware.js +78 -48
  182. package/lib/serialization/ObjectMiddleware.js +78 -29
  183. package/lib/serialization/PlainObjectSerializer.js +1 -1
  184. package/lib/serialization/Serializer.js +15 -10
  185. package/lib/serialization/SerializerMiddleware.js +80 -41
  186. package/lib/serialization/SingleItemMiddleware.js +10 -7
  187. package/lib/serialization/types.js +1 -1
  188. package/lib/sharing/ConsumeSharedModule.js +4 -2
  189. package/lib/sharing/ProvideSharedModule.js +4 -2
  190. package/lib/sharing/ProvideSharedModuleFactory.js +5 -3
  191. package/lib/sharing/utils.js +2 -2
  192. package/lib/stats/DefaultStatsFactoryPlugin.js +80 -78
  193. package/lib/stats/DefaultStatsPresetPlugin.js +43 -23
  194. package/lib/stats/DefaultStatsPrinterPlugin.js +85 -43
  195. package/lib/stats/StatsFactory.js +11 -11
  196. package/lib/stats/StatsPrinter.js +7 -7
  197. package/lib/util/ArrayHelpers.js +2 -4
  198. package/lib/util/ArrayQueue.js +1 -1
  199. package/lib/util/AsyncQueue.js +4 -4
  200. package/lib/util/IterableHelpers.js +1 -1
  201. package/lib/util/LazyBucketSortedSet.js +41 -23
  202. package/lib/util/LazySet.js +3 -2
  203. package/lib/util/MapHelpers.js +1 -1
  204. package/lib/util/ParallelismFactorCalculator.js +1 -1
  205. package/lib/util/Semaphore.js +3 -3
  206. package/lib/util/SetHelpers.js +1 -1
  207. package/lib/util/SortableSet.js +9 -7
  208. package/lib/util/TupleQueue.js +9 -8
  209. package/lib/util/TupleSet.js +2 -2
  210. package/lib/util/WeakTupleMap.js +12 -11
  211. package/lib/util/binarySearchBounds.js +2 -1
  212. package/lib/util/cleverMerge.js +84 -54
  213. package/lib/util/comparators.js +22 -21
  214. package/lib/util/compileBooleanMatcher.js +3 -3
  215. package/lib/util/concatenate.js +6 -4
  216. package/lib/util/create-schema-validation.js +4 -4
  217. package/lib/util/createHash.js +2 -2
  218. package/lib/util/deprecation.js +35 -33
  219. package/lib/util/deterministicGrouping.js +6 -6
  220. package/lib/util/findGraphRoots.js +1 -1
  221. package/lib/util/fs.js +39 -39
  222. package/lib/util/hash/wasm-hash.js +2 -2
  223. package/lib/util/identifier.js +15 -18
  224. package/lib/util/makeSerializable.js +1 -1
  225. package/lib/util/memoize.js +4 -1
  226. package/lib/util/objectToMap.js +3 -2
  227. package/lib/util/processAsyncTree.js +2 -2
  228. package/lib/util/propertyName.js +0 -1
  229. package/lib/util/registerExternalSerializer.js +15 -18
  230. package/lib/util/removeBOM.js +25 -0
  231. package/lib/util/runtime.js +34 -27
  232. package/lib/util/serialization.js +5 -16
  233. package/lib/util/smartGrouping.js +3 -3
  234. package/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js +3 -3
  235. package/lib/wasm-async/AsyncWebAssemblyGenerator.js +11 -0
  236. package/lib/wasm-async/AsyncWebAssemblyJavascriptGenerator.js +10 -0
  237. package/lib/wasm-async/UniversalCompileAsyncWasmPlugin.js +4 -0
  238. package/lib/wasm-sync/WebAssemblyGenerator.js +28 -12
  239. package/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +10 -0
  240. package/lib/wasm-sync/WebAssemblyParser.js +9 -4
  241. package/lib/webworker/ImportScriptsChunkLoadingPlugin.js +3 -0
  242. package/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js +30 -25
  243. package/package.json +19 -17
  244. package/schemas/WebpackOptions.check.js +1 -1
  245. package/schemas/WebpackOptions.json +48 -13
  246. package/schemas/plugins/JsonModulesPluginGenerator.check.d.ts +7 -0
  247. package/schemas/plugins/JsonModulesPluginGenerator.check.js +6 -0
  248. package/schemas/plugins/JsonModulesPluginGenerator.json +11 -0
  249. package/schemas/plugins/SourceMapDevToolPlugin.json +2 -2
  250. package/types.d.ts +918 -615
  251. package/lib/library/ModernModuleLibraryPlugin.js +0 -144
@@ -19,13 +19,14 @@ const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
19
19
  * @param {JavascriptParser} parser the parser
20
20
  * @param {string} value the const value
21
21
  * @param {(string[] | null)=} runtimeRequirements runtime requirements
22
- * @returns {function(Expression): true} plugin function
22
+ * @returns {(expression: Expression) => true} plugin function
23
23
  */
24
24
  module.exports.toConstantDependency = (parser, value, runtimeRequirements) =>
25
25
  function constDependency(expr) {
26
26
  const dep = new ConstDependency(
27
27
  value,
28
- /** @type {Range} */ (expr.range),
28
+ /** @type {Range} */
29
+ (expr.range),
29
30
  runtimeRequirements
30
31
  );
31
32
  dep.loc = /** @type {SourceLocation} */ (expr.loc);
@@ -35,7 +36,7 @@ module.exports.toConstantDependency = (parser, value, runtimeRequirements) =>
35
36
 
36
37
  /**
37
38
  * @param {string} value the string value
38
- * @returns {function(Expression): BasicEvaluatedExpression} plugin function
39
+ * @returns {(expression: Expression) => BasicEvaluatedExpression} plugin function
39
40
  */
40
41
  module.exports.evaluateToString = value =>
41
42
  function stringExpression(expr) {
@@ -46,7 +47,7 @@ module.exports.evaluateToString = value =>
46
47
 
47
48
  /**
48
49
  * @param {number} value the number value
49
- * @returns {function(Expression): BasicEvaluatedExpression} plugin function
50
+ * @returns {(expression: Expression) => BasicEvaluatedExpression} plugin function
50
51
  */
51
52
  module.exports.evaluateToNumber = value =>
52
53
  function stringExpression(expr) {
@@ -57,7 +58,7 @@ module.exports.evaluateToNumber = value =>
57
58
 
58
59
  /**
59
60
  * @param {boolean} value the boolean value
60
- * @returns {function(Expression): BasicEvaluatedExpression} plugin function
61
+ * @returns {(expression: Expression) => BasicEvaluatedExpression} plugin function
61
62
  */
62
63
  module.exports.evaluateToBoolean = value =>
63
64
  function booleanExpression(expr) {
@@ -69,9 +70,9 @@ module.exports.evaluateToBoolean = value =>
69
70
  /**
70
71
  * @param {string} identifier identifier
71
72
  * @param {string} rootInfo rootInfo
72
- * @param {function(): string[]} getMembers getMembers
73
- * @param {boolean|null=} truthy is truthy, null if nullish
74
- * @returns {function(Expression): BasicEvaluatedExpression} callback
73
+ * @param {() => string[]} getMembers getMembers
74
+ * @param {boolean | null=} truthy is truthy, null if nullish
75
+ * @returns {(expression: Expression) => BasicEvaluatedExpression} callback
75
76
  */
76
77
  module.exports.evaluateToIdentifier = (
77
78
  identifier,
@@ -102,7 +103,7 @@ module.exports.evaluateToIdentifier = (
102
103
  /**
103
104
  * @param {JavascriptParser} parser the parser
104
105
  * @param {string} message the message
105
- * @returns {function(Expression): boolean | undefined} callback to handle unsupported expression
106
+ * @returns {(expression: Expression) => boolean | undefined} callback to handle unsupported expression
106
107
  */
107
108
  module.exports.expressionIsUnsupported = (parser, message) =>
108
109
  function unsupportedExpression(expr) {
@@ -88,6 +88,9 @@ module.exports.generateEntryStartup = (
88
88
  let currentModuleIds;
89
89
 
90
90
  for (const [module, entrypoint] of entries) {
91
+ if (!chunkGraph.getModuleSourceTypes(module).has("javascript")) {
92
+ continue;
93
+ }
91
94
  const runtimeChunk =
92
95
  /** @type {Entrypoint} */
93
96
  (entrypoint).getRuntimeChunk();
@@ -162,7 +165,7 @@ module.exports.updateHashForEntryStartup = (
162
165
  /**
163
166
  * @param {Chunk} chunk the chunk
164
167
  * @param {ChunkGraph} chunkGraph the chunk graph
165
- * @param {function(Chunk, ChunkGraph): boolean} filterFn filter function
168
+ * @param {(chunk: Chunk, chunkGraph: ChunkGraph) => boolean} filterFn filter function
166
169
  * @returns {Set<number | string>} initially fulfilled chunk ids
167
170
  */
168
171
  module.exports.getInitialChunkIds = (chunk, chunkGraph, filterFn) => {
@@ -10,16 +10,16 @@ const { register } = require("../util/serialization");
10
10
  /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
11
11
  /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
12
12
  /** @typedef {import("../util/Hash")} Hash */
13
- /** @typedef {import("./JsonModulesPlugin").RawJsonData} RawJsonData */
13
+ /** @typedef {import("./JsonModulesPlugin").JsonValue} JsonValue */
14
14
 
15
15
  class JsonData {
16
16
  /**
17
- * @param {Buffer | RawJsonData} data JSON data
17
+ * @param {Buffer | JsonValue} data JSON data
18
18
  */
19
19
  constructor(data) {
20
20
  /** @type {Buffer | undefined} */
21
21
  this._buffer = undefined;
22
- /** @type {RawJsonData | undefined} */
22
+ /** @type {JsonValue | undefined} */
23
23
  this._data = undefined;
24
24
  if (Buffer.isBuffer(data)) {
25
25
  this._buffer = data;
@@ -29,7 +29,7 @@ class JsonData {
29
29
  }
30
30
 
31
31
  /**
32
- * @returns {RawJsonData|undefined} Raw JSON data
32
+ * @returns {JsonValue | undefined} Raw JSON data
33
33
  */
34
34
  get() {
35
35
  if (this._data === undefined && this._buffer !== undefined) {
@@ -13,6 +13,7 @@ const { JS_TYPES } = require("../ModuleSourceTypesConstants");
13
13
  const RuntimeGlobals = require("../RuntimeGlobals");
14
14
 
15
15
  /** @typedef {import("webpack-sources").Source} Source */
16
+ /** @typedef {import("../../declarations/WebpackOptions").JsonGeneratorOptions} JsonGeneratorOptions */
16
17
  /** @typedef {import("../ExportsInfo")} ExportsInfo */
17
18
  /** @typedef {import("../Generator").GenerateContext} GenerateContext */
18
19
  /** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
@@ -20,10 +21,12 @@ const RuntimeGlobals = require("../RuntimeGlobals");
20
21
  /** @typedef {import("../NormalModule")} NormalModule */
21
22
  /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
22
23
  /** @typedef {import("./JsonData")} JsonData */
23
- /** @typedef {import("./JsonModulesPlugin").RawJsonData} RawJsonData */
24
+ /** @typedef {import("./JsonModulesPlugin").JsonArray} JsonArray */
25
+ /** @typedef {import("./JsonModulesPlugin").JsonObject} JsonObject */
26
+ /** @typedef {import("./JsonModulesPlugin").JsonValue} JsonValue */
24
27
 
25
28
  /**
26
- * @param {RawJsonData} data Raw JSON data
29
+ * @param {JsonValue} data Raw JSON data
27
30
  * @returns {undefined|string} stringified data
28
31
  */
29
32
  const stringifySafe = data => {
@@ -38,30 +41,35 @@ const stringifySafe = data => {
38
41
  };
39
42
 
40
43
  /**
41
- * @param {RawJsonData} data Raw JSON data (always an object or array)
44
+ * @param {JsonObject | JsonArray} data Raw JSON data (always an object or array)
42
45
  * @param {ExportsInfo} exportsInfo exports info
43
46
  * @param {RuntimeSpec} runtime the runtime
44
- * @returns {RawJsonData} reduced data
47
+ * @returns {JsonObject | JsonArray} reduced data
45
48
  */
46
49
  const createObjectForExportsInfo = (data, exportsInfo, runtime) => {
47
50
  if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused)
48
51
  return data;
49
52
  const isArray = Array.isArray(data);
50
- /** @type {RawJsonData} */
53
+ /** @type {JsonObject | JsonArray} */
51
54
  const reducedData = isArray ? [] : {};
52
55
  for (const key of Object.keys(data)) {
53
56
  const exportInfo = exportsInfo.getReadOnlyExportInfo(key);
54
57
  const used = exportInfo.getUsed(runtime);
55
58
  if (used === UsageState.Unused) continue;
56
59
 
57
- /** @type {RawJsonData} */
60
+ // The real type is `JsonObject | JsonArray`, but typescript doesn't work `Object.keys(['string', 'other-string', 'etc'])` properly
61
+ const newData = /** @type {JsonObject} */ (data)[key];
58
62
  const value =
59
- used === UsageState.OnlyPropertiesUsed && exportInfo.exportsInfo
60
- ? createObjectForExportsInfo(data[key], exportInfo.exportsInfo, runtime)
61
- : data[key];
63
+ used === UsageState.OnlyPropertiesUsed &&
64
+ exportInfo.exportsInfo &&
65
+ typeof newData === "object" &&
66
+ newData
67
+ ? createObjectForExportsInfo(newData, exportInfo.exportsInfo, runtime)
68
+ : newData;
62
69
 
63
70
  const name = /** @type {string} */ (exportInfo.getUsedName(key, runtime));
64
- /** @type {Record<string, RawJsonData>} */ (reducedData)[name] = value;
71
+ /** @type {JsonObject} */
72
+ (reducedData)[name] = value;
65
73
  }
66
74
  if (isArray) {
67
75
  const arrayLengthWhenUsed =
@@ -71,8 +79,11 @@ const createObjectForExportsInfo = (data, exportsInfo, runtime) => {
71
79
  : undefined;
72
80
 
73
81
  let sizeObjectMinusArray = 0;
74
- for (let i = 0; i < reducedData.length; i++) {
75
- if (reducedData[i] === undefined) {
82
+ const reducedDataLength =
83
+ /** @type {JsonArray} */
84
+ (reducedData).length;
85
+ for (let i = 0; i < reducedDataLength; i++) {
86
+ if (/** @type {JsonArray} */ (reducedData)[i] === undefined) {
76
87
  sizeObjectMinusArray -= 2;
77
88
  } else {
78
89
  sizeObjectMinusArray += `${i}`.length + 3;
@@ -82,7 +93,7 @@ const createObjectForExportsInfo = (data, exportsInfo, runtime) => {
82
93
  sizeObjectMinusArray +=
83
94
  `${arrayLengthWhenUsed}`.length +
84
95
  8 -
85
- (arrayLengthWhenUsed - reducedData.length) * 2;
96
+ (arrayLengthWhenUsed - reducedDataLength) * 2;
86
97
  }
87
98
  if (sizeObjectMinusArray < 0)
88
99
  return Object.assign(
@@ -94,11 +105,12 @@ const createObjectForExportsInfo = (data, exportsInfo, runtime) => {
94
105
  /** @type {number} */
95
106
  const generatedLength =
96
107
  arrayLengthWhenUsed !== undefined
97
- ? Math.max(arrayLengthWhenUsed, reducedData.length)
98
- : reducedData.length;
108
+ ? Math.max(arrayLengthWhenUsed, reducedDataLength)
109
+ : reducedDataLength;
99
110
  for (let i = 0; i < generatedLength; i++) {
100
- if (reducedData[i] === undefined) {
101
- reducedData[i] = 0;
111
+ if (/** @type {JsonArray} */ (reducedData)[i] === undefined) {
112
+ /** @type {JsonArray} */
113
+ (reducedData)[i] = 0;
102
114
  }
103
115
  }
104
116
  }
@@ -106,6 +118,14 @@ const createObjectForExportsInfo = (data, exportsInfo, runtime) => {
106
118
  };
107
119
 
108
120
  class JsonGenerator extends Generator {
121
+ /**
122
+ * @param {JsonGeneratorOptions} options options
123
+ */
124
+ constructor(options) {
125
+ super();
126
+ this.options = options;
127
+ }
128
+
109
129
  /**
110
130
  * @param {NormalModule} module fresh module
111
131
  * @returns {SourceTypes} available types (do not mutate)
@@ -120,7 +140,7 @@ class JsonGenerator extends Generator {
120
140
  * @returns {number} estimate size of the module
121
141
  */
122
142
  getSize(module, type) {
123
- /** @type {RawJsonData | undefined} */
143
+ /** @type {JsonValue | undefined} */
124
144
  const data =
125
145
  module.buildInfo &&
126
146
  module.buildInfo.jsonData &&
@@ -153,7 +173,7 @@ class JsonGenerator extends Generator {
153
173
  concatenationScope
154
174
  }
155
175
  ) {
156
- /** @type {RawJsonData | undefined} */
176
+ /** @type {JsonValue | undefined} */
157
177
  const data =
158
178
  module.buildInfo &&
159
179
  module.buildInfo.jsonData &&
@@ -166,7 +186,7 @@ class JsonGenerator extends Generator {
166
186
  );
167
187
  }
168
188
  const exportsInfo = moduleGraph.getExportsInfo(module);
169
- /** @type {RawJsonData} */
189
+ /** @type {JsonValue} */
170
190
  const finalJson =
171
191
  typeof data === "object" &&
172
192
  data &&
@@ -176,9 +196,11 @@ class JsonGenerator extends Generator {
176
196
  // Use JSON because JSON.parse() is much faster than JavaScript evaluation
177
197
  const jsonStr = /** @type {string} */ (stringifySafe(finalJson));
178
198
  const jsonExpr =
179
- jsonStr.length > 20 && typeof finalJson === "object"
199
+ this.options.JSONParse &&
200
+ jsonStr.length > 20 &&
201
+ typeof finalJson === "object"
180
202
  ? `/*#__PURE__*/JSON.parse('${jsonStr.replace(/[\\']/g, "\\$&")}')`
181
- : jsonStr;
203
+ : jsonStr.replace(/"__proto__":/g, '["__proto__"]:');
182
204
  /** @type {string} */
183
205
  let content;
184
206
  if (concatenationScope) {
@@ -194,6 +216,16 @@ class JsonGenerator extends Generator {
194
216
  }
195
217
  return new RawSource(content);
196
218
  }
219
+
220
+ /**
221
+ * @param {Error} error the error
222
+ * @param {NormalModule} module module for which the code should be generated
223
+ * @param {GenerateContext} generateContext context for generate
224
+ * @returns {Source | null} generated code
225
+ */
226
+ generateError(error, module, generateContext) {
227
+ return new RawSource(`throw new Error(${JSON.stringify(error.message)});`);
228
+ }
197
229
  }
198
230
 
199
231
  module.exports = JsonGenerator;
@@ -11,7 +11,9 @@ const JsonGenerator = require("./JsonGenerator");
11
11
  const JsonParser = require("./JsonParser");
12
12
 
13
13
  /** @typedef {import("../Compiler")} Compiler */
14
- /** @typedef {Record<string, any>} RawJsonData */
14
+ /** @typedef {import("../util/fs").JsonArray} JsonArray */
15
+ /** @typedef {import("../util/fs").JsonObject} JsonObject */
16
+ /** @typedef {import("../util/fs").JsonValue} JsonValue */
15
17
 
16
18
  const validate = createSchemaValidation(
17
19
  require("../../schemas/plugins/JsonModulesPluginParser.check.js"),
@@ -22,6 +24,15 @@ const validate = createSchemaValidation(
22
24
  }
23
25
  );
24
26
 
27
+ const validateGenerator = createSchemaValidation(
28
+ require("../../schemas/plugins/JsonModulesPluginGenerator.check.js"),
29
+ () => require("../../schemas/plugins/JsonModulesPluginGenerator.json"),
30
+ {
31
+ name: "Json Modules Plugin",
32
+ baseDataPath: "generator"
33
+ }
34
+ );
35
+
25
36
  const PLUGIN_NAME = "JsonModulesPlugin";
26
37
 
27
38
  /**
@@ -46,7 +57,10 @@ class JsonModulesPlugin {
46
57
  });
47
58
  normalModuleFactory.hooks.createGenerator
48
59
  .for(JSON_MODULE_TYPE)
49
- .tap(PLUGIN_NAME, () => new JsonGenerator());
60
+ .tap(PLUGIN_NAME, generatorOptions => {
61
+ validateGenerator(generatorOptions);
62
+ return new JsonGenerator(generatorOptions);
63
+ });
50
64
  }
51
65
  );
52
66
  }
@@ -15,7 +15,7 @@ const JsonData = require("./JsonData");
15
15
  /** @typedef {import("../Module").BuildMeta} BuildMeta */
16
16
  /** @typedef {import("../Parser").ParserState} ParserState */
17
17
  /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
18
- /** @typedef {import("./JsonModulesPlugin").RawJsonData} RawJsonData */
18
+ /** @typedef {import("./JsonModulesPlugin").JsonValue} JsonValue */
19
19
 
20
20
  const getParseJson = memoize(() => require("json-parse-even-better-errors"));
21
21
 
@@ -43,7 +43,7 @@ class JsonParser extends Parser {
43
43
  typeof this.options.parse === "function"
44
44
  ? this.options.parse
45
45
  : getParseJson();
46
- /** @type {Buffer | RawJsonData | undefined} */
46
+ /** @type {Buffer | JsonValue | undefined} */
47
47
  let data;
48
48
  try {
49
49
  data =
@@ -55,7 +55,7 @@ class JsonParser extends Parser {
55
55
  `Cannot parse JSON: ${/** @type {Error} */ (err).message}`
56
56
  );
57
57
  }
58
- const jsonData = new JsonData(/** @type {Buffer | RawJsonData} */ (data));
58
+ const jsonData = new JsonData(/** @type {Buffer | JsonValue} */ (data));
59
59
  const buildInfo = /** @type {BuildInfo} */ (state.module.buildInfo);
60
60
  buildInfo.jsonData = jsonData;
61
61
  buildInfo.strict = true;
@@ -64,7 +64,11 @@ class JsonParser extends Parser {
64
64
  buildMeta.defaultObject =
65
65
  typeof data === "object" ? "redirect-warn" : false;
66
66
  state.module.addDependency(
67
- new JsonExportsDependency(jsonData, this.options.exportsDepth)
67
+ new JsonExportsDependency(
68
+ jsonData,
69
+ /** @type {number} */
70
+ (this.options.exportsDepth)
71
+ )
68
72
  );
69
73
  return state;
70
74
  }
@@ -32,14 +32,18 @@ const COMMON_LIBRARY_NAME_MESSAGE =
32
32
  * @property {T} options
33
33
  */
34
34
 
35
+ /**
36
+ * @typedef {object} AbstractLibraryPluginOptions
37
+ * @property {string} pluginName name of the plugin
38
+ * @property {LibraryType} type used library type
39
+ */
40
+
35
41
  /**
36
42
  * @template T
37
43
  */
38
44
  class AbstractLibraryPlugin {
39
45
  /**
40
- * @param {object} options options
41
- * @param {string} options.pluginName name of the plugin
42
- * @param {LibraryType} options.type used library type
46
+ * @param {AbstractLibraryPluginOptions} options options
43
47
  */
44
48
  constructor({ pluginName, type }) {
45
49
  this._pluginName = pluginName;
@@ -19,7 +19,6 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
19
19
  /** @typedef {import("../Chunk")} Chunk */
20
20
  /** @typedef {import("../Compilation")} Compilation */
21
21
  /** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */
22
- /** @typedef {import("../Compiler")} Compiler */
23
22
  /** @typedef {import("../Module")} Module */
24
23
  /** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
25
24
  /** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */
@@ -303,13 +302,42 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin {
303
302
  this._getPrefix(compilation).length,
304
303
  true
305
304
  );
305
+
306
+ /** @type {string[]} */
307
+ const provided = [];
306
308
  for (const exportInfo of exportsInfo.orderedExports) {
307
309
  if (!exportInfo.provided) continue;
308
310
  const nameAccess = propertyAccess([exportInfo.name]);
309
311
  result.add(
310
312
  `${exportTarget}${nameAccess} = ${RuntimeGlobals.exports}${exportAccess}${nameAccess};\n`
311
313
  );
314
+ provided.push(exportInfo.name);
312
315
  }
316
+
317
+ const webpackExportTarget = accessWithInit(
318
+ fullNameResolved,
319
+ this._getPrefix(compilation).length,
320
+ true
321
+ );
322
+ /** @type {string} */
323
+ let exports = RuntimeGlobals.exports;
324
+ if (exportAccess) {
325
+ result.add(
326
+ `var __webpack_exports_export__ = ${RuntimeGlobals.exports}${exportAccess};\n`
327
+ );
328
+ exports = "__webpack_exports_export__";
329
+ }
330
+ result.add(`for(var __webpack_i__ in ${exports}) {\n`);
331
+ const hasProvided = provided.length > 0;
332
+ if (hasProvided) {
333
+ result.add(
334
+ ` if (${JSON.stringify(provided)}.indexOf(__webpack_i__) === -1) {\n`
335
+ );
336
+ }
337
+ result.add(
338
+ ` ${hasProvided ? " " : ""}${webpackExportTarget}[__webpack_i__] = ${exports}[__webpack_i__];\n`
339
+ );
340
+ result.add(hasProvided ? " }\n}\n" : "\n");
313
341
  result.add(
314
342
  `Object.defineProperty(${exportTarget}, "__esModule", { value: true });\n`
315
343
  );
@@ -80,7 +80,8 @@ class EnableLibraryPlugin {
80
80
  new ExportPropertyTemplatePlugin({
81
81
  type,
82
82
  nsObjectUsed: !["module", "modern-module"].includes(type),
83
- runtimeExportsUsed: type !== "modern-module"
83
+ runtimeExportsUsed: !["module", "modern-module"].includes(type),
84
+ renderStartupUsed: !["module", "modern-module"].includes(type)
84
85
  }).apply(compiler);
85
86
  };
86
87
  switch (type) {
@@ -212,6 +213,9 @@ class EnableLibraryPlugin {
212
213
  compiler.options.output.iife = true;
213
214
 
214
215
  class WarnFalseIifeUmdPlugin {
216
+ /**
217
+ * @param {Compiler} compiler the compiler instance
218
+ */
215
219
  apply(compiler) {
216
220
  compiler.hooks.thisCompilation.tap(
217
221
  "WarnFalseIifeUmdPlugin",
@@ -249,7 +253,8 @@ class EnableLibraryPlugin {
249
253
  }).apply(compiler);
250
254
  break;
251
255
  }
252
- case "module": {
256
+ case "module":
257
+ case "modern-module": {
253
258
  enableExportProperty();
254
259
  const ModuleLibraryPlugin = require("./ModuleLibraryPlugin");
255
260
  new ModuleLibraryPlugin({
@@ -257,14 +262,6 @@ class EnableLibraryPlugin {
257
262
  }).apply(compiler);
258
263
  break;
259
264
  }
260
- case "modern-module": {
261
- enableExportProperty();
262
- const ModernModuleLibraryPlugin = require("./ModernModuleLibraryPlugin");
263
- new ModernModuleLibraryPlugin({
264
- type
265
- }).apply(compiler);
266
- break;
267
- }
268
265
  default:
269
266
  throw new Error(`Unsupported library type ${type}.
270
267
  Plugins which provide custom library types must call EnableLibraryPlugin.setEnabled(compiler, type) to disable this error.`);
@@ -31,6 +31,7 @@ const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
31
31
  * @property {LibraryType} type
32
32
  * @property {boolean} nsObjectUsed the namespace object is used
33
33
  * @property {boolean} runtimeExportsUsed runtime exports are used
34
+ * @property {boolean} renderStartupUsed render startup is used
34
35
  */
35
36
  /**
36
37
  * @typedef {ExportPropertyLibraryPluginParsed} T
@@ -40,13 +41,14 @@ class ExportPropertyLibraryPlugin extends AbstractLibraryPlugin {
40
41
  /**
41
42
  * @param {ExportPropertyLibraryPluginOptions} options options
42
43
  */
43
- constructor({ type, nsObjectUsed, runtimeExportsUsed }) {
44
+ constructor({ type, nsObjectUsed, runtimeExportsUsed, renderStartupUsed }) {
44
45
  super({
45
46
  pluginName: "ExportPropertyLibraryPlugin",
46
47
  type
47
48
  });
48
49
  this.nsObjectUsed = nsObjectUsed;
49
50
  this.runtimeExportsUsed = runtimeExportsUsed;
51
+ this.renderStartupUsed = renderStartupUsed;
50
52
  }
51
53
 
52
54
  /**
@@ -109,6 +111,7 @@ class ExportPropertyLibraryPlugin extends AbstractLibraryPlugin {
109
111
  * @returns {Source} source with library export
110
112
  */
111
113
  renderStartup(source, module, renderContext, { options }) {
114
+ if (!this.renderStartupUsed) return source;
112
115
  if (!options.export) return source;
113
116
  const postfix = `${RuntimeGlobals.exports} = ${
114
117
  RuntimeGlobals.exports