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