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