@@ -3,13 +3,41 @@ import pEachSeries from 'p-each-series';
3
3
import micromatch from 'micromatch' ;
4
4
import crypto from 'crypto' ;
5
5
import globby from 'globby' ;
6
+ import path from 'path' ;
7
+ import webpack from 'webpack' ;
6
8
import {
7
9
ensureTrailingSlash ,
10
+ fsReadFileAsync ,
8
11
handleUrl ,
9
12
resolveOutput ,
10
13
resolvePublicPath ,
11
14
} from './utils' ;
12
15
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
+
13
41
export default class AddAssetHtmlPlugin {
14
42
constructor ( assets = [ ] ) {
15
43
this . assets = Array . isArray ( assets ) ? assets . slice ( ) . reverse ( ) : [ assets ] ;
@@ -22,7 +50,7 @@ export default class AddAssetHtmlPlugin {
22
50
let beforeGenerationHook ;
23
51
let alterAssetTagsHook ;
24
52
25
- if ( HtmlWebpackPlugin . version == = 4 ) {
53
+ if ( HtmlWebpackPlugin . version > = 4 ) {
26
54
const hooks = HtmlWebpackPlugin . getHooks ( compilation ) ;
27
55
28
56
beforeGenerationHook = hooks . beforeAssetTagGeneration ;
@@ -105,10 +133,11 @@ export default class AddAssetHtmlPlugin {
105
133
}
106
134
}
107
135
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 ) ;
112
141
113
142
let suffix = '' ;
114
143
if ( hash ) {
@@ -133,7 +162,7 @@ export default class AddAssetHtmlPlugin {
133
162
const relatedFiles = await globby ( `${ filepath } .*` ) ;
134
163
await Promise . all (
135
164
relatedFiles . sort ( ) . map ( async relatedFile => {
136
- const addedMapFilename = await htmlPluginData . plugin . addFileToAssets (
165
+ const addedMapFilename = await addFileToAssets (
137
166
relatedFile ,
138
167
compilation ,
139
168
) ;
0 commit comments