@@ -3,13 +3,41 @@ import pEachSeries from 'p-each-series';
33import micromatch from 'micromatch' ;
44import crypto from 'crypto' ;
55import globby from 'globby' ;
6+ import path from 'path' ;
7+ import webpack from 'webpack' ;
68import {
79 ensureTrailingSlash ,
10+ fsReadFileAsync ,
811 handleUrl ,
912 resolveOutput ,
1013 resolvePublicPath ,
1114} from './utils' ;
1215
16+ /* istanbul ignore next: webpack 5 not in unit test mocks */
17+ /**
18+ * Pushes the content of the given filename to the compilation assets
19+ * @param {string } filename
20+ * @param {WebpackCompilation } compilation
21+ * @returns {Promise<string> } file basename
22+ */
23+ function addFileToAssetsWebpack5 ( filename , compilation ) {
24+ const resolvedFilename = path . resolve ( compilation . compiler . context , filename ) ;
25+
26+ return fsReadFileAsync ( resolvedFilename )
27+ . then ( source => new webpack . sources . RawSource ( source , true ) )
28+ . catch ( ( ) =>
29+ Promise . reject (
30+ new Error ( `HtmlWebpackPlugin: could not load file ${ resolvedFilename } ` ) ,
31+ ) ,
32+ )
33+ . then ( rawSource => {
34+ const basename = path . basename ( resolvedFilename ) ;
35+ compilation . fileDependencies . add ( resolvedFilename ) ;
36+ compilation . emitAsset ( basename , rawSource ) ;
37+ return basename ;
38+ } ) ;
39+ }
40+
1341export default class AddAssetHtmlPlugin {
1442 constructor ( assets = [ ] ) {
1543 this . assets = Array . isArray ( assets ) ? assets . slice ( ) . reverse ( ) : [ assets ] ;
@@ -22,7 +50,7 @@ export default class AddAssetHtmlPlugin {
2250 let beforeGenerationHook ;
2351 let alterAssetTagsHook ;
2452
25- if ( HtmlWebpackPlugin . version == = 4 ) {
53+ if ( HtmlWebpackPlugin . version > = 4 ) {
2654 const hooks = HtmlWebpackPlugin . getHooks ( compilation ) ;
2755
2856 beforeGenerationHook = hooks . beforeAssetTagGeneration ;
@@ -105,10 +133,11 @@ export default class AddAssetHtmlPlugin {
105133 }
106134 }
107135
108- const addedFilename = await htmlPluginData . plugin . addFileToAssets (
109- filepath ,
110- compilation ,
111- ) ;
136+ const addFileToAssets =
137+ htmlPluginData . plugin . addFileToAssets ||
138+ /* istanbul ignore next: webpack 5 not in unit test mocks */ addFileToAssetsWebpack5 ;
139+
140+ const addedFilename = await addFileToAssets ( filepath , compilation ) ;
112141
113142 let suffix = '' ;
114143 if ( hash ) {
@@ -133,7 +162,7 @@ export default class AddAssetHtmlPlugin {
133162 const relatedFiles = await globby ( `${ filepath } .*` ) ;
134163 await Promise . all (
135164 relatedFiles . sort ( ) . map ( async relatedFile => {
136- const addedMapFilename = await htmlPluginData . plugin . addFileToAssets (
165+ const addedMapFilename = await addFileToAssets (
137166 relatedFile ,
138167 compilation ,
139168 ) ;
0 commit comments