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