55
66"use strict" ;
77
8+ const { SyncBailHook } = require ( "tapable" ) ;
89const { OriginalSource, RawSource } = require ( "webpack-sources" ) ;
910const ConcatenationScope = require ( "./ConcatenationScope" ) ;
1011const EnvironmentNotSupportAsyncWarning = require ( "./EnvironmentNotSupportAsyncWarning" ) ;
@@ -629,6 +630,14 @@ const getSourceForDefaultCase = (optional, request, runtimeTemplate) => {
629630/** @typedef {Record<string, string | string[]> } RequestRecord */
630631/** @typedef {string | string[] | RequestRecord } ExternalModuleRequest */
631632
633+ /**
634+ * @typedef {object } ExternalModuleHooks
635+ * @property {SyncBailHook<[Chunk, Compilation], boolean> } chunkCondition
636+ */
637+
638+ /** @type {WeakMap<Compilation, ExternalModuleHooks> } */
639+ const compilationHooksMap = new WeakMap ( ) ;
640+
632641class ExternalModule extends Module {
633642 /**
634643 * @param {ExternalModuleRequest } request request
@@ -650,6 +659,21 @@ class ExternalModule extends Module {
650659 this . dependencyMeta = dependencyMeta ;
651660 }
652661
662+ /**
663+ * @param {Compilation } compilation the compilation
664+ * @returns {ExternalModuleHooks } the attached hooks
665+ */
666+ static getCompilationHooks ( compilation ) {
667+ let hooks = compilationHooksMap . get ( compilation ) ;
668+ if ( hooks === undefined ) {
669+ hooks = {
670+ chunkCondition : new SyncBailHook ( [ "chunk" , "compilation" ] )
671+ } ;
672+ compilationHooksMap . set ( compilation , hooks ) ;
673+ }
674+ return hooks ;
675+ }
676+
653677 /**
654678 * @returns {SourceTypes } types available (do not mutate)
655679 */
@@ -679,12 +703,21 @@ class ExternalModule extends Module {
679703 /**
680704 * @param {Chunk } chunk the chunk which condition should be checked
681705 * @param {Compilation } compilation the compilation
682- * @returns {boolean } true, if the chunk is ok for the module
706+ * @returns {boolean } true if the module can be placed in the chunk
683707 */
684- chunkCondition ( chunk , { chunkGraph } ) {
685- return this . externalType === "css-import"
686- ? true
687- : chunkGraph . getNumberOfEntryModules ( chunk ) > 0 ;
708+ chunkCondition ( chunk , compilation ) {
709+ const { chunkCondition } = ExternalModule . getCompilationHooks ( compilation ) ;
710+ const condition = chunkCondition . call ( chunk , compilation ) ;
711+ if ( condition !== undefined ) return condition ;
712+
713+ const type = this . _resolveExternalType ( this . externalType ) ;
714+
715+ // For `import()` externals, keep them in the initial chunk to avoid loading
716+ // them asynchronously twice and to improve runtime performance.
717+ if ( [ "css-import" , "module" ] . includes ( type ) ) {
718+ return true ;
719+ }
720+ return compilation . chunkGraph . getNumberOfEntryModules ( chunk ) > 0 ;
688721 }
689722
690723 /**
0 commit comments