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