1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | 'use strict';
|
10 |
|
11 | const promisify = require('util').promisify;
|
12 |
|
13 | const vm = require('vm');
|
14 | const fs = require('fs');
|
15 | const _ = require('lodash');
|
16 | const path = require('path');
|
17 | const loaderUtils = require('loader-utils');
|
18 | const { CachedChildCompilation } = require('./lib/cached-child-compiler');
|
19 |
|
20 | const { createHtmlTagObject, htmlTagObjectToString, HtmlTagArray } = require('./lib/html-tags');
|
21 |
|
22 | const prettyError = require('./lib/errors.js');
|
23 | const chunkSorter = require('./lib/chunksorter.js');
|
24 | const getHtmlWebpackPluginHooks = require('./lib/hooks.js').getHtmlWebpackPluginHooks;
|
25 | const { assert } = require('console');
|
26 |
|
27 | const fsReadFileAsync = promisify(fs.readFile);
|
28 |
|
29 | class HtmlWebpackPlugin {
|
30 | |
31 |
|
32 |
|
33 | constructor (options) {
|
34 |
|
35 | this.userOptions = options || {};
|
36 | this.version = HtmlWebpackPlugin.version;
|
37 | }
|
38 |
|
39 | apply (compiler) {
|
40 |
|
41 | compiler.hooks.initialize.tap('HtmlWebpackPlugin', () => {
|
42 | const userOptions = this.userOptions;
|
43 |
|
44 |
|
45 |
|
46 | const defaultOptions = {
|
47 | template: 'auto',
|
48 | templateContent: false,
|
49 | templateParameters: templateParametersGenerator,
|
50 | filename: 'index.html',
|
51 | publicPath: userOptions.publicPath === undefined ? 'auto' : userOptions.publicPath,
|
52 | hash: false,
|
53 | inject: userOptions.scriptLoading === 'blocking' ? 'body' : 'head',
|
54 | scriptLoading: 'defer',
|
55 | compile: true,
|
56 | favicon: false,
|
57 | minify: 'auto',
|
58 | cache: true,
|
59 | showErrors: true,
|
60 | chunks: 'all',
|
61 | excludeChunks: [],
|
62 | chunksSortMode: 'auto',
|
63 | meta: {},
|
64 | base: false,
|
65 | title: 'Webpack App',
|
66 | xhtml: false
|
67 | };
|
68 |
|
69 |
|
70 | const options = Object.assign(defaultOptions, userOptions);
|
71 | this.options = options;
|
72 |
|
73 |
|
74 | assert(options.scriptLoading === 'defer' || options.scriptLoading === 'blocking', 'scriptLoading needs to be set to "defer" or "blocking');
|
75 | assert(options.inject === true || options.inject === false || options.inject === 'head' || options.inject === 'body', 'inject needs to be set to true, false, "head" or "body');
|
76 |
|
77 |
|
78 | if (!userOptions.template && options.templateContent === false && options.meta) {
|
79 | const defaultMeta = {
|
80 |
|
81 | viewport: 'width=device-width, initial-scale=1'
|
82 | };
|
83 | options.meta = Object.assign({}, options.meta, defaultMeta, userOptions.meta);
|
84 | }
|
85 |
|
86 |
|
87 | const userOptionFilename = userOptions.filename || defaultOptions.filename;
|
88 | const filenameFunction = typeof userOptionFilename === 'function'
|
89 | ? userOptionFilename
|
90 |
|
91 | : (entryName) => userOptionFilename.replace(/\[name\]/g, entryName);
|
92 |
|
93 |
|
94 | const entryNames = Object.keys(compiler.options.entry);
|
95 | const outputFileNames = new Set((entryNames.length ? entryNames : ['main']).map(filenameFunction));
|
96 |
|
97 |
|
98 | const entryOptions = Array.from(outputFileNames).map((filename) => ({
|
99 | ...options,
|
100 | filename
|
101 | }));
|
102 |
|
103 |
|
104 | entryOptions.forEach((instanceOptions) => {
|
105 | hookIntoCompiler(compiler, instanceOptions, this);
|
106 | });
|
107 | });
|
108 | }
|
109 |
|
110 | |
111 |
|
112 |
|
113 |
|
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 |
|
120 |
|
121 | evaluateCompilationResult (source, publicPath, templateFilename) {
|
122 | if (!source) {
|
123 | return Promise.reject(new Error('The child compilation didn\'t provide a result'));
|
124 | }
|
125 |
|
126 |
|
127 | if (source.indexOf('HTML_WEBPACK_PLUGIN_RESULT') >= 0) {
|
128 | source += ';\nHTML_WEBPACK_PLUGIN_RESULT';
|
129 | }
|
130 | const templateWithoutLoaders = templateFilename.replace(/^.+!/, '').replace(/\?.+$/, '');
|
131 | const vmContext = vm.createContext({
|
132 | ...global,
|
133 | HTML_WEBPACK_PLUGIN: true,
|
134 | require: require,
|
135 | htmlWebpackPluginPublicPath:
|
136 | publicPath,
|
137 | URL: require('url').URL,
|
138 | __filename: templateWithoutLoaders
|
139 | });
|
140 | const vmScript = new vm.Script(source, { filename: templateWithoutLoaders });
|
141 |
|
142 | let newSource;
|
143 | try {
|
144 | newSource = vmScript.runInContext(vmContext);
|
145 | } catch (e) {
|
146 | return Promise.reject(e);
|
147 | }
|
148 | if (typeof newSource === 'object' && newSource.__esModule && newSource.default) {
|
149 | newSource = newSource.default;
|
150 | }
|
151 | return typeof newSource === 'string' || typeof newSource === 'function'
|
152 | ? Promise.resolve(newSource)
|
153 | : Promise.reject(new Error('The loader "' + templateWithoutLoaders + '" didn\'t return html.'));
|
154 | }
|
155 | }
|
156 |
|
157 |
|
158 |
|
159 |
|
160 |
|
161 |
|
162 |
|
163 |
|
164 | function hookIntoCompiler (compiler, options, plugin) {
|
165 | const webpack = compiler.webpack;
|
166 |
|
167 |
|
168 | let assetJson;
|
169 | |
170 |
|
171 |
|
172 |
|
173 |
|
174 | let previousEmittedAssets = [];
|
175 |
|
176 | options.template = getFullTemplatePath(options.template, compiler.context);
|
177 |
|
178 |
|
179 | const childCompilerPlugin = new CachedChildCompilation(compiler);
|
180 | if (!options.templateContent) {
|
181 | childCompilerPlugin.addEntry(options.template);
|
182 | }
|
183 |
|
184 |
|
185 |
|
186 | const filename = options.filename;
|
187 | if (path.resolve(filename) === path.normalize(filename)) {
|
188 | const outputPath = (compiler.options.output.path);
|
189 | options.filename = path.relative(outputPath, filename);
|
190 | }
|
191 |
|
192 |
|
193 |
|
194 |
|
195 | options.filename = options.filename.replace(/\[(?:(\w+):)?contenthash(?::([a-z]+\d*))?(?::(\d+))?\]/ig, (match) => {
|
196 | return match.replace('contenthash', 'templatehash');
|
197 | });
|
198 |
|
199 |
|
200 |
|
201 | const isProductionLikeMode = compiler.options.mode === 'production' || !compiler.options.mode;
|
202 |
|
203 | const minify = options.minify;
|
204 | if (minify === true || (minify === 'auto' && isProductionLikeMode)) {
|
205 |
|
206 | options.minify = {
|
207 |
|
208 | collapseWhitespace: true,
|
209 | keepClosingSlash: true,
|
210 | removeComments: true,
|
211 | removeRedundantAttributes: true,
|
212 | removeScriptTypeAttributes: true,
|
213 | removeStyleLinkTypeAttributes: true,
|
214 | useShortDoctype: true
|
215 | };
|
216 | }
|
217 |
|
218 | compiler.hooks.thisCompilation.tap('HtmlWebpackPlugin',
|
219 | |
220 |
|
221 |
|
222 |
|
223 | (compilation) => {
|
224 | compilation.hooks.processAssets.tapAsync(
|
225 | {
|
226 | name: 'HtmlWebpackPlugin',
|
227 | stage:
|
228 | |
229 |
|
230 |
|
231 | webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
|
232 | },
|
233 | |
234 |
|
235 |
|
236 |
|
237 |
|
238 | (compilationAssets, callback) => {
|
239 |
|
240 | const entryNames = Array.from(compilation.entrypoints.keys());
|
241 | const filteredEntryNames = filterChunks(entryNames, options.chunks, options.excludeChunks);
|
242 | const sortedEntryNames = sortEntryChunks(filteredEntryNames, options.chunksSortMode, compilation);
|
243 |
|
244 | const templateResult = options.templateContent
|
245 | ? { mainCompilationHash: compilation.hash }
|
246 | : childCompilerPlugin.getCompilationEntryResult(options.template);
|
247 |
|
248 | if ('error' in templateResult) {
|
249 | compilation.errors.push(prettyError(templateResult.error, compiler.context).toString());
|
250 | }
|
251 |
|
252 | const compiledEntries = 'compiledEntry' in templateResult ? {
|
253 | hash: templateResult.compiledEntry.hash,
|
254 | chunk: templateResult.compiledEntry.entry
|
255 | } : {
|
256 | hash: templateResult.mainCompilationHash
|
257 | };
|
258 |
|
259 | const childCompilationOutputName = compilation.getAssetPath(options.filename, compiledEntries);
|
260 |
|
261 |
|
262 |
|
263 | const isCompilationCached = templateResult.mainCompilationHash !== compilation.hash;
|
264 |
|
265 |
|
266 | const htmlPublicPath = getPublicPath(compilation, childCompilationOutputName, options.publicPath);
|
267 |
|
268 |
|
269 | const assets = htmlWebpackPluginAssets(compilation, sortedEntryNames, htmlPublicPath);
|
270 |
|
271 |
|
272 | const newAssetJson = JSON.stringify(getAssetFiles(assets));
|
273 | if (isCompilationCached && options.cache && assetJson === newAssetJson) {
|
274 | previousEmittedAssets.forEach(({ name, html }) => {
|
275 | compilation.emitAsset(name, new webpack.sources.RawSource(html, false));
|
276 | });
|
277 | return callback();
|
278 | } else {
|
279 | previousEmittedAssets = [];
|
280 | assetJson = newAssetJson;
|
281 | }
|
282 |
|
283 |
|
284 |
|
285 |
|
286 | const assetsPromise = getFaviconPublicPath(options.favicon, compilation, assets.publicPath)
|
287 | .then((faviconPath) => {
|
288 | assets.favicon = faviconPath;
|
289 | return getHtmlWebpackPluginHooks(compilation).beforeAssetTagGeneration.promise({
|
290 | assets: assets,
|
291 | outputName: childCompilationOutputName,
|
292 | plugin: plugin
|
293 | });
|
294 | });
|
295 |
|
296 |
|
297 | const assetTagGroupsPromise = assetsPromise
|
298 |
|
299 | .then(({ assets }) => getHtmlWebpackPluginHooks(compilation).alterAssetTags.promise({
|
300 | assetTags: {
|
301 | scripts: generatedScriptTags(assets.js),
|
302 | styles: generateStyleTags(assets.css),
|
303 | meta: [
|
304 | ...generateBaseTag(options.base),
|
305 | ...generatedMetaTags(options.meta),
|
306 | ...generateFaviconTags(assets.favicon)
|
307 | ]
|
308 | },
|
309 | outputName: childCompilationOutputName,
|
310 | publicPath: htmlPublicPath,
|
311 | plugin: plugin
|
312 | }))
|
313 | .then(({ assetTags }) => {
|
314 |
|
315 | const scriptTarget = options.inject === 'head' ||
|
316 | (options.inject !== 'body' && options.scriptLoading !== 'blocking') ? 'head' : 'body';
|
317 |
|
318 | const assetGroups = generateAssetGroups(assetTags, scriptTarget);
|
319 |
|
320 | return getHtmlWebpackPluginHooks(compilation).alterAssetTagGroups.promise({
|
321 | headTags: assetGroups.headTags,
|
322 | bodyTags: assetGroups.bodyTags,
|
323 | outputName: childCompilationOutputName,
|
324 | publicPath: htmlPublicPath,
|
325 | plugin: plugin
|
326 | });
|
327 | });
|
328 |
|
329 |
|
330 | const templateEvaluationPromise = Promise.resolve()
|
331 | .then(() => {
|
332 | if ('error' in templateResult) {
|
333 | return options.showErrors ? prettyError(templateResult.error, compiler.context).toHtml() : 'ERROR';
|
334 | }
|
335 |
|
336 | if (options.templateContent !== false) {
|
337 | return options.templateContent;
|
338 | }
|
339 |
|
340 |
|
341 | return ('compiledEntry' in templateResult)
|
342 | ? plugin.evaluateCompilationResult(templateResult.compiledEntry.content, htmlPublicPath, options.template)
|
343 | : Promise.reject(new Error('Child compilation contained no compiledEntry'));
|
344 | });
|
345 | const templateExectutionPromise = Promise.all([assetsPromise, assetTagGroupsPromise, templateEvaluationPromise])
|
346 |
|
347 | .then(([assetsHookResult, assetTags, compilationResult]) => typeof compilationResult !== 'function'
|
348 | ? compilationResult
|
349 | : executeTemplate(compilationResult, assetsHookResult.assets, { headTags: assetTags.headTags, bodyTags: assetTags.bodyTags }, compilation));
|
350 |
|
351 | const injectedHtmlPromise = Promise.all([assetTagGroupsPromise, templateExectutionPromise])
|
352 |
|
353 | .then(([assetTags, html]) => {
|
354 | const pluginArgs = { html, headTags: assetTags.headTags, bodyTags: assetTags.bodyTags, plugin: plugin, outputName: childCompilationOutputName };
|
355 | return getHtmlWebpackPluginHooks(compilation).afterTemplateExecution.promise(pluginArgs);
|
356 | })
|
357 | .then(({ html, headTags, bodyTags }) => {
|
358 | return postProcessHtml(html, assets, { headTags, bodyTags });
|
359 | });
|
360 |
|
361 | const emitHtmlPromise = injectedHtmlPromise
|
362 |
|
363 | .then((html) => {
|
364 | const pluginArgs = { html, plugin: plugin, outputName: childCompilationOutputName };
|
365 | return getHtmlWebpackPluginHooks(compilation).beforeEmit.promise(pluginArgs)
|
366 | .then(result => result.html);
|
367 | })
|
368 | .catch(err => {
|
369 |
|
370 |
|
371 | compilation.errors.push(prettyError(err, compiler.context).toString());
|
372 | return options.showErrors ? prettyError(err, compiler.context).toHtml() : 'ERROR';
|
373 | })
|
374 | .then(html => {
|
375 |
|
376 |
|
377 |
|
378 | const finalOutputName = childCompilationOutputName.replace(/\[(?:(\w+):)?templatehash(?::([a-z]+\d*))?(?::(\d+))?\]/ig, (_, hashType, digestType, maxLength) => {
|
379 | return loaderUtils.getHashDigest(Buffer.from(html, 'utf8'), hashType, digestType, parseInt(maxLength, 10));
|
380 | });
|
381 |
|
382 | compilation.emitAsset(finalOutputName, new webpack.sources.RawSource(html, false));
|
383 | previousEmittedAssets.push({ name: finalOutputName, html });
|
384 | return finalOutputName;
|
385 | })
|
386 | .then((finalOutputName) => getHtmlWebpackPluginHooks(compilation).afterEmit.promise({
|
387 | outputName: finalOutputName,
|
388 | plugin: plugin
|
389 | }).catch(err => {
|
390 | console.error(err);
|
391 | return null;
|
392 | }).then(() => null));
|
393 |
|
394 |
|
395 |
|
396 | emitHtmlPromise.then(() => {
|
397 | callback();
|
398 | });
|
399 | });
|
400 | });
|
401 |
|
402 | |
403 |
|
404 |
|
405 |
|
406 |
|
407 |
|
408 |
|
409 |
|
410 |
|
411 |
|
412 |
|
413 |
|
414 |
|
415 |
|
416 |
|
417 |
|
418 | function getTemplateParameters (compilation, assets, assetTags) {
|
419 | const templateParameters = options.templateParameters;
|
420 | if (templateParameters === false) {
|
421 | return Promise.resolve({});
|
422 | }
|
423 | if (typeof templateParameters !== 'function' && typeof templateParameters !== 'object') {
|
424 | throw new Error('templateParameters has to be either a function or an object');
|
425 | }
|
426 | const templateParameterFunction = typeof templateParameters === 'function'
|
427 |
|
428 | ? templateParameters
|
429 |
|
430 | : (compilation, assets, assetTags, options) => Object.assign({},
|
431 | templateParametersGenerator(compilation, assets, assetTags, options),
|
432 | templateParameters
|
433 | );
|
434 | const preparedAssetTags = {
|
435 | headTags: prepareAssetTagGroupForRendering(assetTags.headTags),
|
436 | bodyTags: prepareAssetTagGroupForRendering(assetTags.bodyTags)
|
437 | };
|
438 | return Promise
|
439 | .resolve()
|
440 | .then(() => templateParameterFunction(compilation, assets, preparedAssetTags, options));
|
441 | }
|
442 |
|
443 | |
444 |
|
445 |
|
446 |
|
447 |
|
448 |
|
449 |
|
450 |
|
451 |
|
452 |
|
453 |
|
454 |
|
455 |
|
456 |
|
457 |
|
458 |
|
459 |
|
460 |
|
461 |
|
462 | function executeTemplate (templateFunction, assets, assetTags, compilation) {
|
463 |
|
464 | const templateParamsPromise = getTemplateParameters(compilation, assets, assetTags);
|
465 | return templateParamsPromise.then((templateParams) => {
|
466 | try {
|
467 |
|
468 |
|
469 | return templateFunction(templateParams);
|
470 | } catch (e) {
|
471 | compilation.errors.push(new Error('Template execution failed: ' + e));
|
472 | return Promise.reject(e);
|
473 | }
|
474 | });
|
475 | }
|
476 |
|
477 | |
478 |
|
479 |
|
480 |
|
481 |
|
482 |
|
483 |
|
484 |
|
485 |
|
486 |
|
487 |
|
488 |
|
489 |
|
490 |
|
491 | function postProcessHtml (html, assets, assetTags) {
|
492 | if (typeof html !== 'string') {
|
493 | return Promise.reject(new Error('Expected html to be a string but got ' + JSON.stringify(html)));
|
494 | }
|
495 | const htmlAfterInjection = options.inject
|
496 | ? injectAssetsIntoHtml(html, assets, assetTags)
|
497 | : html;
|
498 | const htmlAfterMinification = minifyHtml(htmlAfterInjection);
|
499 | return Promise.resolve(htmlAfterMinification);
|
500 | }
|
501 |
|
502 | |
503 |
|
504 |
|
505 |
|
506 |
|
507 |
|
508 |
|
509 | function addFileToAssets (filename, compilation) {
|
510 | filename = path.resolve(compilation.compiler.context, filename);
|
511 | return fsReadFileAsync(filename)
|
512 | .then(source => new webpack.sources.RawSource(source, false))
|
513 | .catch(() => Promise.reject(new Error('HtmlWebpackPlugin: could not load file ' + filename)))
|
514 | .then(rawSource => {
|
515 | const basename = path.basename(filename);
|
516 | compilation.fileDependencies.add(filename);
|
517 | compilation.emitAsset(basename, rawSource);
|
518 | return basename;
|
519 | });
|
520 | }
|
521 |
|
522 | |
523 |
|
524 |
|
525 |
|
526 |
|
527 |
|
528 | function sortEntryChunks (entryNames, sortMode, compilation) {
|
529 |
|
530 | if (typeof sortMode === 'function') {
|
531 | return entryNames.sort(sortMode);
|
532 | }
|
533 |
|
534 | if (typeof chunkSorter[sortMode] !== 'undefined') {
|
535 | return chunkSorter[sortMode](entryNames, compilation, options);
|
536 | }
|
537 | throw new Error('"' + sortMode + '" is not a valid chunk sort mode');
|
538 | }
|
539 |
|
540 | |
541 |
|
542 |
|
543 |
|
544 |
|
545 |
|
546 | function filterChunks (chunks, includedChunks, excludedChunks) {
|
547 | return chunks.filter(chunkName => {
|
548 |
|
549 | if (Array.isArray(includedChunks) && includedChunks.indexOf(chunkName) === -1) {
|
550 | return false;
|
551 | }
|
552 |
|
553 | if (Array.isArray(excludedChunks) && excludedChunks.indexOf(chunkName) !== -1) {
|
554 | return false;
|
555 | }
|
556 |
|
557 | return true;
|
558 | });
|
559 | }
|
560 |
|
561 | |
562 |
|
563 |
|
564 |
|
565 |
|
566 |
|
567 |
|
568 |
|
569 |
|
570 | function getPublicPath (compilation, childCompilationOutputName, customPublicPath) {
|
571 | const compilationHash = compilation.hash;
|
572 |
|
573 | |
574 |
|
575 |
|
576 |
|
577 |
|
578 | const webpackPublicPath = compilation.getAssetPath(compilation.outputOptions.publicPath, { hash: compilationHash });
|
579 |
|
580 |
|
581 | const isPublicPathDefined = webpackPublicPath !== 'auto';
|
582 |
|
583 | let publicPath =
|
584 |
|
585 | customPublicPath !== 'auto'
|
586 | ? customPublicPath
|
587 | : (isPublicPathDefined
|
588 |
|
589 | ? webpackPublicPath
|
590 |
|
591 | : path.relative(path.resolve(compilation.options.output.path, path.dirname(childCompilationOutputName)), compilation.options.output.path)
|
592 | .split(path.sep).join('/')
|
593 | );
|
594 |
|
595 | if (publicPath.length && publicPath.substr(-1, 1) !== '/') {
|
596 | publicPath += '/';
|
597 | }
|
598 |
|
599 | return publicPath;
|
600 | }
|
601 |
|
602 | |
603 |
|
604 |
|
605 |
|
606 |
|
607 |
|
608 |
|
609 |
|
610 |
|
611 |
|
612 |
|
613 |
|
614 |
|
615 |
|
616 | function htmlWebpackPluginAssets (compilation, entryNames, publicPath) {
|
617 | const compilationHash = compilation.hash;
|
618 | |
619 |
|
620 |
|
621 |
|
622 |
|
623 |
|
624 |
|
625 |
|
626 |
|
627 | const assets = {
|
628 |
|
629 | publicPath,
|
630 |
|
631 | js: [],
|
632 |
|
633 | css: [],
|
634 |
|
635 | manifest: Object.keys(compilation.assets).find(assetFile => path.extname(assetFile) === '.appcache'),
|
636 |
|
637 | favicon: undefined
|
638 | };
|
639 |
|
640 |
|
641 | if (options.hash && assets.manifest) {
|
642 | assets.manifest = appendHash(assets.manifest, compilationHash);
|
643 | }
|
644 |
|
645 |
|
646 | const entryPointPublicPathMap = {};
|
647 | const extensionRegexp = /\.(css|js|mjs)(\?|$)/;
|
648 | for (let i = 0; i < entryNames.length; i++) {
|
649 | const entryName = entryNames[i];
|
650 |
|
651 | const entryPointUnfilteredFiles = compilation.entrypoints.get(entryName).getFiles();
|
652 |
|
653 | const entryPointFiles = entryPointUnfilteredFiles.filter((chunkFile) => {
|
654 |
|
655 |
|
656 |
|
657 | const asset = compilation.getAsset && compilation.getAsset(chunkFile);
|
658 | if (!asset) {
|
659 | return true;
|
660 | }
|
661 |
|
662 | const assetMetaInformation = asset.info || {};
|
663 | return !(assetMetaInformation.hotModuleReplacement || assetMetaInformation.development);
|
664 | });
|
665 |
|
666 |
|
667 |
|
668 |
|
669 | const entryPointPublicPaths = entryPointFiles
|
670 | .map(chunkFile => {
|
671 | const entryPointPublicPath = publicPath + urlencodePath(chunkFile);
|
672 | return options.hash
|
673 | ? appendHash(entryPointPublicPath, compilationHash)
|
674 | : entryPointPublicPath;
|
675 | });
|
676 |
|
677 | entryPointPublicPaths.forEach((entryPointPublicPath) => {
|
678 | const extMatch = extensionRegexp.exec(entryPointPublicPath);
|
679 |
|
680 | if (!extMatch) {
|
681 | return;
|
682 | }
|
683 |
|
684 |
|
685 | if (entryPointPublicPathMap[entryPointPublicPath]) {
|
686 | return;
|
687 | }
|
688 | entryPointPublicPathMap[entryPointPublicPath] = true;
|
689 |
|
690 | const ext = extMatch[1] === 'mjs' ? 'js' : extMatch[1];
|
691 | assets[ext].push(entryPointPublicPath);
|
692 | });
|
693 | }
|
694 | return assets;
|
695 | }
|
696 |
|
697 | |
698 |
|
699 |
|
700 |
|
701 |
|
702 |
|
703 |
|
704 |
|
705 |
|
706 | function getFaviconPublicPath (faviconFilePath, compilation, publicPath) {
|
707 | if (!faviconFilePath) {
|
708 | return Promise.resolve(undefined);
|
709 | }
|
710 | return addFileToAssets(faviconFilePath, compilation)
|
711 | .then((faviconName) => {
|
712 | const faviconPath = publicPath + faviconName;
|
713 | if (options.hash) {
|
714 | return appendHash(faviconPath, compilation.hash);
|
715 | }
|
716 | return faviconPath;
|
717 | });
|
718 | }
|
719 |
|
720 | |
721 |
|
722 |
|
723 |
|
724 |
|
725 | function generatedScriptTags (jsAssets) {
|
726 | return jsAssets.map(scriptAsset => ({
|
727 | tagName: 'script',
|
728 | voidTag: false,
|
729 | meta: { plugin: 'html-webpack-plugin' },
|
730 | attributes: {
|
731 | defer: options.scriptLoading !== 'blocking',
|
732 | src: scriptAsset
|
733 | }
|
734 | }));
|
735 | }
|
736 |
|
737 | |
738 |
|
739 |
|
740 |
|
741 |
|
742 | function generateStyleTags (cssAssets) {
|
743 | return cssAssets.map(styleAsset => ({
|
744 | tagName: 'link',
|
745 | voidTag: true,
|
746 | meta: { plugin: 'html-webpack-plugin' },
|
747 | attributes: {
|
748 | href: styleAsset,
|
749 | rel: 'stylesheet'
|
750 | }
|
751 | }));
|
752 | }
|
753 |
|
754 | |
755 |
|
756 |
|
757 |
|
758 |
|
759 |
|
760 |
|
761 |
|
762 | function generateBaseTag (baseOption) {
|
763 | if (baseOption === false) {
|
764 | return [];
|
765 | } else {
|
766 | return [{
|
767 | tagName: 'base',
|
768 | voidTag: true,
|
769 | meta: { plugin: 'html-webpack-plugin' },
|
770 | attributes: (typeof baseOption === 'string') ? {
|
771 | href: baseOption
|
772 | } : baseOption
|
773 | }];
|
774 | }
|
775 | }
|
776 |
|
777 | |
778 |
|
779 |
|
780 |
|
781 |
|
782 |
|
783 |
|
784 |
|
785 |
|
786 |
|
787 | function generatedMetaTags (metaOptions) {
|
788 | if (metaOptions === false) {
|
789 | return [];
|
790 | }
|
791 |
|
792 |
|
793 |
|
794 | const metaTagAttributeObjects = Object.keys(metaOptions)
|
795 | .map((metaName) => {
|
796 | const metaTagContent = metaOptions[metaName];
|
797 | return (typeof metaTagContent === 'string') ? {
|
798 | name: metaName,
|
799 | content: metaTagContent
|
800 | } : metaTagContent;
|
801 | })
|
802 | .filter((attribute) => attribute !== false);
|
803 |
|
804 |
|
805 | return metaTagAttributeObjects.map((metaTagAttributes) => {
|
806 | if (metaTagAttributes === false) {
|
807 | throw new Error('Invalid meta tag');
|
808 | }
|
809 | return {
|
810 | tagName: 'meta',
|
811 | voidTag: true,
|
812 | meta: { plugin: 'html-webpack-plugin' },
|
813 | attributes: metaTagAttributes
|
814 | };
|
815 | });
|
816 | }
|
817 |
|
818 | |
819 |
|
820 |
|
821 |
|
822 |
|
823 | function generateFaviconTags (faviconPath) {
|
824 | if (!faviconPath) {
|
825 | return [];
|
826 | }
|
827 | return [{
|
828 | tagName: 'link',
|
829 | voidTag: true,
|
830 | meta: { plugin: 'html-webpack-plugin' },
|
831 | attributes: {
|
832 | rel: 'icon',
|
833 | href: faviconPath
|
834 | }
|
835 | }];
|
836 | }
|
837 |
|
838 | |
839 |
|
840 |
|
841 |
|
842 |
|
843 |
|
844 |
|
845 |
|
846 |
|
847 |
|
848 |
|
849 |
|
850 |
|
851 |
|
852 | function generateAssetGroups (assetTags, scriptTarget) {
|
853 |
|
854 | const result = {
|
855 | headTags: [
|
856 | ...assetTags.meta,
|
857 | ...assetTags.styles
|
858 | ],
|
859 | bodyTags: []
|
860 | };
|
861 |
|
862 |
|
863 | if (scriptTarget === 'body') {
|
864 | result.bodyTags.push(...assetTags.scripts);
|
865 | } else {
|
866 |
|
867 |
|
868 | const insertPosition = options.scriptLoading === 'blocking' ? result.headTags.length : assetTags.meta.length;
|
869 | result.headTags.splice(insertPosition, 0, ...assetTags.scripts);
|
870 | }
|
871 | return result;
|
872 | }
|
873 |
|
874 | |
875 |
|
876 |
|
877 |
|
878 |
|
879 |
|
880 |
|
881 | function prepareAssetTagGroupForRendering (assetTagGroup) {
|
882 | const xhtml = options.xhtml;
|
883 | return HtmlTagArray.from(assetTagGroup.map((assetTag) => {
|
884 | const copiedAssetTag = Object.assign({}, assetTag);
|
885 | copiedAssetTag.toString = function () {
|
886 | return htmlTagObjectToString(this, xhtml);
|
887 | };
|
888 | return copiedAssetTag;
|
889 | }));
|
890 | }
|
891 |
|
892 | |
893 |
|
894 |
|
895 |
|
896 |
|
897 |
|
898 |
|
899 |
|
900 |
|
901 |
|
902 |
|
903 |
|
904 |
|
905 |
|
906 | function injectAssetsIntoHtml (html, assets, assetTags) {
|
907 | const htmlRegExp = /(<html[^>]*>)/i;
|
908 | const headRegExp = /(<\/head\s*>)/i;
|
909 | const bodyRegExp = /(<\/body\s*>)/i;
|
910 | const body = assetTags.bodyTags.map((assetTagObject) => htmlTagObjectToString(assetTagObject, options.xhtml));
|
911 | const head = assetTags.headTags.map((assetTagObject) => htmlTagObjectToString(assetTagObject, options.xhtml));
|
912 |
|
913 | if (body.length) {
|
914 | if (bodyRegExp.test(html)) {
|
915 |
|
916 | html = html.replace(bodyRegExp, match => body.join('') + match);
|
917 | } else {
|
918 |
|
919 | html += body.join('');
|
920 | }
|
921 | }
|
922 |
|
923 | if (head.length) {
|
924 |
|
925 | if (!headRegExp.test(html)) {
|
926 | if (!htmlRegExp.test(html)) {
|
927 | html = '<head></head>' + html;
|
928 | } else {
|
929 | html = html.replace(htmlRegExp, match => match + '<head></head>');
|
930 | }
|
931 | }
|
932 |
|
933 |
|
934 | html = html.replace(headRegExp, match => head.join('') + match);
|
935 | }
|
936 |
|
937 |
|
938 | if (assets.manifest) {
|
939 | html = html.replace(/(<html[^>]*)(>)/i, (match, start, end) => {
|
940 |
|
941 | if (/\smanifest\s*=/.test(match)) {
|
942 | return match;
|
943 | }
|
944 | return start + ' manifest="' + assets.manifest + '"' + end;
|
945 | });
|
946 | }
|
947 | return html;
|
948 | }
|
949 |
|
950 | |
951 |
|
952 |
|
953 |
|
954 |
|
955 |
|
956 | function appendHash (url, hash) {
|
957 | if (!url) {
|
958 | return url;
|
959 | }
|
960 | return url + (url.indexOf('?') === -1 ? '?' : '&') + hash;
|
961 | }
|
962 |
|
963 | |
964 |
|
965 |
|
966 |
|
967 |
|
968 |
|
969 |
|
970 |
|
971 |
|
972 |
|
973 |
|
974 |
|
975 |
|
976 |
|
977 |
|
978 |
|
979 |
|
980 |
|
981 |
|
982 |
|
983 |
|
984 | function urlencodePath (filePath) {
|
985 |
|
986 |
|
987 |
|
988 |
|
989 |
|
990 | const queryStringStart = filePath.indexOf('?');
|
991 | const urlPath = queryStringStart === -1 ? filePath : filePath.substr(0, queryStringStart);
|
992 | const queryString = filePath.substr(urlPath.length);
|
993 |
|
994 | const encodedUrlPath = urlPath.split('/').map(encodeURIComponent).join('/');
|
995 | return encodedUrlPath + queryString;
|
996 | }
|
997 |
|
998 | |
999 |
|
1000 |
|
1001 |
|
1002 |
|
1003 |
|
1004 |
|
1005 | function getFullTemplatePath (template, context) {
|
1006 | if (template === 'auto') {
|
1007 | template = path.resolve(context, 'src/index.ejs');
|
1008 | if (!fs.existsSync(template)) {
|
1009 | template = path.join(__dirname, 'default_index.ejs');
|
1010 | }
|
1011 | }
|
1012 |
|
1013 | if (template.indexOf('!') === -1) {
|
1014 | template = require.resolve('./lib/loader.js') + '!' + path.resolve(context, template);
|
1015 | }
|
1016 |
|
1017 | return template.replace(
|
1018 | /([!])([^/\\][^!?]+|[^/\\!?])($|\?[^!?\n]+$)/,
|
1019 | (match, prefix, filepath, postfix) => prefix + path.resolve(filepath) + postfix);
|
1020 | }
|
1021 |
|
1022 | |
1023 |
|
1024 |
|
1025 |
|
1026 |
|
1027 |
|
1028 |
|
1029 |
|
1030 |
|
1031 | function minifyHtml (html) {
|
1032 | if (typeof options.minify !== 'object') {
|
1033 | return html;
|
1034 | }
|
1035 | try {
|
1036 | return require('html-minifier-terser').minify(html, options.minify);
|
1037 | } catch (e) {
|
1038 | const isParseError = String(e.message).indexOf('Parse Error') === 0;
|
1039 | if (isParseError) {
|
1040 | e.message = 'html-webpack-plugin could not minify the generated output.\n' +
|
1041 | 'In production mode the html minifcation is enabled by default.\n' +
|
1042 | 'If you are not generating a valid html output please disable it manually.\n' +
|
1043 | 'You can do so by adding the following setting to your HtmlWebpackPlugin config:\n|\n|' +
|
1044 | ' minify: false\n|\n' +
|
1045 | 'See https://github.com/jantimon/html-webpack-plugin#options for details.\n\n' +
|
1046 | 'For parser dedicated bugs please create an issue here:\n' +
|
1047 | 'https://danielruf.github.io/html-minifier-terser/' +
|
1048 | '\n' + e.message;
|
1049 | }
|
1050 | throw e;
|
1051 | }
|
1052 | }
|
1053 |
|
1054 | |
1055 |
|
1056 |
|
1057 |
|
1058 | function getAssetFiles (assets) {
|
1059 | const files = _.uniq(Object.keys(assets).filter(assetType => assetType !== 'chunks' && assets[assetType]).reduce((files, assetType) => files.concat(assets[assetType]), []));
|
1060 | files.sort();
|
1061 | return files;
|
1062 | }
|
1063 | }
|
1064 |
|
1065 |
|
1066 |
|
1067 |
|
1068 |
|
1069 |
|
1070 |
|
1071 |
|
1072 |
|
1073 |
|
1074 |
|
1075 |
|
1076 |
|
1077 |
|
1078 |
|
1079 |
|
1080 |
|
1081 |
|
1082 |
|
1083 |
|
1084 |
|
1085 | function templateParametersGenerator (compilation, assets, assetTags, options) {
|
1086 | return {
|
1087 | compilation: compilation,
|
1088 | webpackConfig: compilation.options,
|
1089 | htmlWebpackPlugin: {
|
1090 | tags: assetTags,
|
1091 | files: assets,
|
1092 | options: options
|
1093 | }
|
1094 | };
|
1095 | }
|
1096 |
|
1097 |
|
1098 |
|
1099 |
|
1100 |
|
1101 | HtmlWebpackPlugin.version = 5;
|
1102 |
|
1103 |
|
1104 |
|
1105 |
|
1106 |
|
1107 |
|
1108 | HtmlWebpackPlugin.getHooks = getHtmlWebpackPluginHooks;
|
1109 | HtmlWebpackPlugin.createHtmlTagObject = createHtmlTagObject;
|
1110 |
|
1111 | module.exports = HtmlWebpackPlugin;
|