@@ -13,14 +13,32 @@ interface Compilation {
13
13
assets : { [ key : string ] : Asset }
14
14
}
15
15
16
+ interface ReplaceConfig {
17
+ position ?: 'before' | 'after'
18
+ removeTarget ?: boolean
19
+ target : string
20
+ }
21
+
16
22
interface Config {
17
23
filter ?( fileName : string ) : boolean
24
+ replace ?: ReplaceConfig
18
25
}
19
26
27
+ const DEFAULT_REPLACE_CONFIG : ReplaceConfig = {
28
+ target : '</head>'
29
+ } ;
30
+
20
31
export default class Plugin
21
32
{
22
- static addStyle ( html : string , style : string ) {
23
- return html . replace ( '</head>' , `<style>${ style } </style></head>` ) ;
33
+ static addStyle ( html : string , style : string , replaceConfig : ReplaceConfig ) {
34
+ const styleString = `<style>${ style } </style>` ;
35
+ const replaceValues = [ styleString , replaceConfig . target ] ;
36
+
37
+ if ( replaceConfig . position === 'after' ) {
38
+ replaceValues . reverse ( )
39
+ }
40
+
41
+ return html . replace ( replaceConfig . target , replaceValues . join ( '' ) ) ;
24
42
}
25
43
26
44
static removeLinkTag ( html : string , cssFileName : string ) {
@@ -30,15 +48,17 @@ export default class Plugin
30
48
) ;
31
49
}
32
50
33
- private config : Config ;
51
+ static cleanUp ( html : string , replaceConfig : ReplaceConfig ) {
52
+ return replaceConfig . removeTarget
53
+ ? html . replace ( replaceConfig . target , '' )
54
+ : html ;
55
+ }
34
56
35
57
private css : File = { } ;
36
58
37
59
private html : File = { } ;
38
60
39
- constructor ( config : Config = { } ) {
40
- this . config = config ;
41
- }
61
+ constructor ( private readonly config : Config = { } ) { }
42
62
43
63
private filter ( fileName : string ) : boolean {
44
64
if ( typeof this . config . filter === 'function' ) {
@@ -67,14 +87,18 @@ export default class Plugin
67
87
68
88
private process ( { assets } : Compilation , { output } : Configuration ) {
69
89
const publicPath = ( output && output . publicPath ) || '' ;
90
+ const { replace : replaceConfig = DEFAULT_REPLACE_CONFIG } = this . config ;
91
+
70
92
Object . keys ( this . html ) . forEach ( ( htmlFileName ) => {
71
93
let html = this . html [ htmlFileName ] ;
72
94
73
95
Object . keys ( this . css ) . forEach ( ( key ) => {
74
- html = Plugin . addStyle ( html , this . css [ key ] ) ;
96
+ html = Plugin . addStyle ( html , this . css [ key ] , replaceConfig ) ;
75
97
html = Plugin . removeLinkTag ( html , publicPath + key ) ;
76
98
} ) ;
77
99
100
+ html = Plugin . cleanUp ( html , replaceConfig ) ;
101
+
78
102
assets [ htmlFileName ] = {
79
103
source ( ) { return html } ,
80
104
size ( ) { return html . length } ,
@@ -94,4 +118,4 @@ export default class Plugin
94
118
function is ( filenameExtension : string ) {
95
119
const reg = new RegExp ( `\.${ filenameExtension } $` ) ;
96
120
return ( fileName : string ) => reg . test ( fileName ) ;
97
- }
121
+ }
0 commit comments