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