@@ -13,14 +13,32 @@ interface Compilation {
1313 assets : { [ key : string ] : Asset }
1414}
1515
16+ interface ReplaceConfig {
17+ position ?: 'before' | 'after'
18+ removeTarget ?: boolean
19+ target : string
20+ }
21+
1622interface Config {
1723 filter ?( fileName : string ) : boolean
24+ replace ?: ReplaceConfig
1825}
1926
27+ const DEFAULT_REPLACE_CONFIG : ReplaceConfig = {
28+ target : '</head>'
29+ } ;
30+
2031export default class Plugin
2132{
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 ( '' ) ) ;
2442 }
2543
2644 static removeLinkTag ( html : string , cssFileName : string ) {
@@ -30,15 +48,17 @@ export default class Plugin
3048 ) ;
3149 }
3250
33- private config : Config ;
51+ static cleanUp ( html : string , replaceConfig : ReplaceConfig ) {
52+ return replaceConfig . removeTarget
53+ ? html . replace ( replaceConfig . target , '' )
54+ : html ;
55+ }
3456
3557 private css : File = { } ;
3658
3759 private html : File = { } ;
3860
39- constructor ( config : Config = { } ) {
40- this . config = config ;
41- }
61+ constructor ( private readonly config : Config = { } ) { }
4262
4363 private filter ( fileName : string ) : boolean {
4464 if ( typeof this . config . filter === 'function' ) {
@@ -67,14 +87,18 @@ export default class Plugin
6787
6888 private process ( { assets } : Compilation , { output } : Configuration ) {
6989 const publicPath = ( output && output . publicPath ) || '' ;
90+ const { replace : replaceConfig = DEFAULT_REPLACE_CONFIG } = this . config ;
91+
7092 Object . keys ( this . html ) . forEach ( ( htmlFileName ) => {
7193 let html = this . html [ htmlFileName ] ;
7294
7395 Object . keys ( this . css ) . forEach ( ( key ) => {
74- html = Plugin . addStyle ( html , this . css [ key ] ) ;
96+ html = Plugin . addStyle ( html , this . css [ key ] , replaceConfig ) ;
7597 html = Plugin . removeLinkTag ( html , publicPath + key ) ;
7698 } ) ;
7799
100+ html = Plugin . cleanUp ( html , replaceConfig ) ;
101+
78102 assets [ htmlFileName ] = {
79103 source ( ) { return html } ,
80104 size ( ) { return html . length } ,
@@ -94,4 +118,4 @@ export default class Plugin
94118function is ( filenameExtension : string ) {
95119 const reg = new RegExp ( `\.${ filenameExtension } $` ) ;
96120 return ( fileName : string ) => reg . test ( fileName ) ;
97- }
121+ }
0 commit comments