@@ -3,37 +3,51 @@ import { parseTemplate } from '../parser/parseTemplate.js';
33
44// Define the loader options type
55interface LoaderOptions {
6- title ?: string ;
7- favicon ?: string ;
8- headMetaTags ?: string [ ] ;
9- headStyles ?: string [ ] ;
10- headScripts ?: string [ ] ;
11- headInlineScripts ?: string [ ] ;
12- bodyScripts ?: string [ ] ;
13- bodyInlineScripts ?: string [ ] ;
6+ force ?: boolean ;
147}
158
169export default function htmlLoader (
1710 this : LoaderContext < LoaderOptions > ,
1811 source : string
1912) : string {
2013 // Get and validate options
21- const options = this . getOptions ;
14+ const options = this . getOptions ( ) ;
15+ const force = options . force || false ;
2216
23- // Skip .js files (unless it's explicitly enforced)
24- if ( ! / \. h t m l $ / . test ( this . resourcePath ) ) {
17+ const allLoadersButThisOne = this . loaders . filter (
18+ ( loader ) => loader . normal !== module . exports
19+ ) ;
20+
21+ // This loader shouldn't kick in if there is any other loader (unless it's explicitly enforced)
22+ if ( allLoadersButThisOne . length > 0 && ! force ) {
2523 return source ;
2624 }
2725
28- // Example transformation
29- const transformedSource = parseTemplate ( source ) ;
26+ // Allow only one html-webpack-plugin loader to allow loader options in the webpack config
27+ const htmlWebpackPluginLoaders = this . loaders . filter (
28+ ( loader ) => loader . normal === module . exports
29+ ) ;
3030
31- // You can use this.emitFile to emit additional files
32- // this.emitFile('output.txt', 'Some content');
31+ const lastHtmlWebpackPluginLoader =
32+ htmlWebpackPluginLoaders [ htmlWebpackPluginLoaders . length - 1 ] ;
33+ if ( this . loaders [ this . loaderIndex ] !== lastHtmlWebpackPluginLoader ) {
34+ return source ;
35+ }
3336
34- // You can use this.callback for async operations
35- // this.callback(null, transformedSource, sourceMap, meta);
37+ // Skip .js files (unless it's explicitly enforced)
38+ if ( ! / \. h t m l $ / . test ( this . resourcePath ) ) {
39+ return source ;
40+ }
3641
37- // Return the transformed source
38- return `export default ${ JSON . stringify ( transformedSource ) } ` ;
42+ // Convert the source into a string that can be executed by vm.Script
43+ return [
44+ 'const { TemplateParser } = eval("require")(' +
45+ JSON . stringify ( require . resolve ( '../index.cjs' ) ) +
46+ ');' ,
47+ 'const parseTemplate = ' + parseTemplate . toString ( ) + ';' ,
48+ 'const source = ' + JSON . stringify ( source ) + ';' ,
49+ 'module.exports = (function(templateParams) { ' ,
50+ 'return parseTemplate(source, templateParams || {});' ,
51+ '});' ,
52+ ] . join ( '' ) ;
3953}
0 commit comments