1+ import path from 'path' ;
12import { Compilation } from 'webpack' ;
23import type { Compiler , WebpackPluginInstance } from 'webpack' ;
34import htmlWebpackPlugin from 'html-webpack-plugin' ;
@@ -37,7 +38,7 @@ class HtmlInlineScriptPlugin implements WebpackPluginInstance {
3738 const {
3839 scriptMatchPattern = [ / .+ [ . ] j s $ / ] ,
3940 htmlMatchPattern = [ / .+ [ . ] h t m l $ / ] ,
40- assetPreservePattern = [ ] ,
41+ assetPreservePattern = [ ]
4142 } = options ;
4243
4344 this . scriptMatchPattern = scriptMatchPattern ;
@@ -59,7 +60,6 @@ class HtmlInlineScriptPlugin implements WebpackPluginInstance {
5960 return this . assetPreservePattern . some ( ( test ) => assetName . match ( test ) ) ;
6061 }
6162
62-
6363 shouldProcessHtml (
6464 templateName : string
6565 ) : boolean {
@@ -102,18 +102,48 @@ class HtmlInlineScriptPlugin implements WebpackPluginInstance {
102102 } ;
103103 }
104104
105- apply ( compiler : Compiler ) : void {
106- let publicPath = compiler . options ?. output ?. publicPath as string || '' ;
105+ getPublicPath (
106+ compilation : Compilation ,
107+ htmlFileName : string ,
108+ customPublicPath : string
109+ ) : string {
110+ const webpackPublicPath = compilation . getAssetPath (
111+ compilation . outputOptions . publicPath as string ,
112+ { hash : compilation . hash }
113+ ) ;
114+ // Webpack 5 introduced "auto" as default value
115+ const isPublicPathDefined = webpackPublicPath !== 'auto' ;
116+
117+ let publicPath = '' ;
118+
119+ if ( customPublicPath !== 'auto' ) {
120+ // If the html-webpack-plugin options contain a custom public path uset it
121+ publicPath = customPublicPath ;
122+ } else if ( isPublicPathDefined ) {
123+ // If a hard coded public path exists in webpack config use it
124+ publicPath = webpackPublicPath ;
125+ } else if ( compilation . options . output . path ) {
126+ // If no public path for webpack and html-webpack-plugin was set get a relative url path
127+ publicPath = path . relative (
128+ path . resolve ( compilation . options . output . path , path . dirname ( htmlFileName ) ) ,
129+ compilation . options . output . path
130+ ) . split ( path . sep ) . join ( '/' ) ;
131+ }
107132
108133 if ( publicPath && ! publicPath . endsWith ( '/' ) ) {
109134 publicPath += '/' ;
110135 }
111136
137+ return publicPath ;
138+ }
139+
140+ apply ( compiler : Compiler ) : void {
112141 compiler . hooks . compilation . tap ( `${ PLUGIN_PREFIX } _compilation` , ( compilation ) => {
113142 const hooks = htmlWebpackPlugin . getHooks ( compilation ) ;
114143
115144 hooks . alterAssetTags . tap ( `${ PLUGIN_PREFIX } _alterAssetTags` , ( data ) => {
116145 const htmlFileName = data . plugin . options ?. filename ;
146+ const publicPath = this . getPublicPath ( compilation , data . outputName , data . publicPath ) ;
117147
118148 if ( htmlFileName && ! this . shouldProcessHtml ( htmlFileName ) ) {
119149 this . ignoredHtmlFiles . push ( htmlFileName ) ;
0 commit comments