@@ -63,8 +63,38 @@ The available options are:
6363 } ;
6464 }
6565
66+ getCommonChunks ( allChunks , compilation ) {
67+ const asyncOrNoSelectedChunk = this . selectedChunks === false || this . async ;
68+
69+ // we have specified chunk names
70+ if ( this . chunkNames ) {
71+ // map chunks by chunkName for quick access
72+ const optimizedChunkMap = allChunks . reduce ( ( map , chunk ) => {
73+ map . set ( chunk . name , chunk ) ;
74+ return map ;
75+ } , new Map ( ) ) ;
76+
77+ // Ensure we have a chunk per specified chunk name.
78+ // Reuse existing chunks if possible
79+ return this . chunkNames . map ( chunkName => {
80+ if ( optimizedChunkMap . has ( chunkName ) ) {
81+ return optimizedChunkMap . get ( chunkName ) ;
82+ }
83+ // add the filtered chunks to the compilation
84+ return compilation . addChunk ( chunkName ) ;
85+ } ) ;
86+ }
87+
88+ // we dont have named chunks specified, so we just take all of them
89+ if ( asyncOrNoSelectedChunk ) {
90+ return allChunks ;
91+ }
92+
93+ // that is not supposed to happen, lets throw
94+ throw new Error ( "Invalid chunkNames argument" ) ;
95+ }
96+
6697 apply ( compiler ) {
67- const chunkNames = this . chunkNames ;
6898 const filenameTemplate = this . filenameTemplate ;
6999 const minChunks = this . minChunks ;
70100 const selectedChunks = this . selectedChunks ;
@@ -77,20 +107,8 @@ The available options are:
77107 if ( compilation [ ident ] ) return ;
78108 compilation [ ident ] = true ;
79109
80- let commonChunks ;
81- if ( ! chunkNames && ( selectedChunks === false || asyncOption ) ) {
82- commonChunks = chunks ;
83- } else if ( Array . isArray ( chunkNames ) || typeof chunkNames === "string" ) {
84- commonChunks = [ ] . concat ( chunkNames ) . map ( ( chunkName ) => {
85- let chunk = chunks . filter ( ( chunk ) => chunk . name === chunkName ) [ 0 ] ;
86- if ( ! chunk ) {
87- chunk = compilation . addChunk ( chunkName ) ;
88- }
89- return chunk ;
90- } ) ;
91- } else {
92- throw new Error ( "Invalid chunkNames argument" ) ;
93- }
110+ const commonChunks = this . formCommonChunks ( chunks , compilation ) ;
111+
94112 commonChunks . forEach ( function processCommonChunk ( commonChunk , idx ) {
95113 let usedChunks ;
96114 if ( Array . isArray ( selectedChunks ) ) {
0 commit comments