html-webpack-plugin 4.2.2 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,48 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ # [4.5.0](https://github.com/jantimon/html-webpack-plugin/compare/v4.4.1...v4.5.0) (2020-09-21)
6
+
7
+
8
+ ### Features
9
+
10
+ * Add publicPath option to overrule the default path generation ([#1516](https://github.com/jantimon/html-webpack-plugin/issues/1516)) ([19b5122](https://github.com/jantimon/html-webpack-plugin/commit/19b5122))
11
+ * update webpack dependency range to allow installing webpack 5 beta ([f3ccdd5](https://github.com/jantimon/html-webpack-plugin/commit/f3ccdd5)), closes [#1504](https://github.com/jantimon/html-webpack-plugin/issues/1504)
12
+
13
+
14
+
15
+ ## [4.4.1](https://github.com/jantimon/html-webpack-plugin/compare/v4.4.0...v4.4.1) (2020-08-30)
16
+
17
+
18
+ ### Bug Fixes
19
+
20
+ * broken typings.d.ts in v4.4.0 ([#1503](https://github.com/jantimon/html-webpack-plugin/issues/1503)) ([98ad756](https://github.com/jantimon/html-webpack-plugin/commit/98ad756))
21
+
22
+
23
+
24
+ # [4.4.0](https://github.com/jantimon/html-webpack-plugin/compare/v4.3.0...v4.4.0) (2020-08-30)
25
+
26
+
27
+ ### Bug Fixes
28
+
29
+ * fix typos in comments ([#1484](https://github.com/jantimon/html-webpack-plugin/issues/1484)) ([6b0711e](https://github.com/jantimon/html-webpack-plugin/commit/6b0711e))
30
+
31
+
32
+ ### Features
33
+
34
+ * added v5 compilation support and deleted depreciation warnings ([4ae7be8](https://github.com/jantimon/html-webpack-plugin/commit/4ae7be8)), closes [#1454](https://github.com/jantimon/html-webpack-plugin/issues/1454)
35
+
36
+
37
+
38
+ # [4.3.0](https://github.com/jantimon/html-webpack-plugin/compare/v4.2.2...v4.3.0) (2020-04-30)
39
+
40
+
41
+ ### Features
42
+
43
+ * Allow to use console.log inside templates ([c3f2fdc](https://github.com/jantimon/html-webpack-plugin/commit/c3f2fdc))
44
+
45
+
46
+
5
47
  ## [4.2.2](https://github.com/jantimon/html-webpack-plugin/compare/v4.2.1...v4.2.2) (2020-04-30)
6
48
 
7
49
 
package/README.md CHANGED
@@ -78,6 +78,7 @@ The `html-webpack-plugin` provides [hooks](https://github.com/jantimon/html-webp
78
78
  * [html-webpack-link-type-plugin](https://github.com/steadyapp/html-webpack-link-type-plugin) adds a configurable mimetype to resources injected as links (such as adding type="text/css" to external stylesheets) for compatibility with "strict mode".
79
79
  * [csp-html-webpack-plugin](https://github.com/slackhq/csp-html-webpack-plugin) to add [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) meta tags to the HTML output
80
80
  * [webpack-nomodule-plugin](https://github.com/swimmadude66/webpack-nomodule-plugin) allows you to add a `nomodule` attribute to specific injected scripts, which prevents the scripts from being loaded by newer browsers. Good for limiting loads of polyfills.
81
+ * [html-webpack-skip-assets-plugin](https://github.com/swimmadude66/html-webpack-skip-assets-plugin) Skip adding certain output files to the html file. Built as a drop-in replacement for [html-webpack-exclude-assets-plugin](https://www.npmjs.com/package/html-webpack-exclude-assets-plugin) and works with newer [html-webpack-plugin](https://github.com/jantimon/html-webpack-plugin) versions
81
82
 
82
83
 
83
84
  <h2 align="center">Usage</h2>
@@ -137,6 +138,7 @@ Allowed values are as follows
137
138
  |**`templateContent`**|`{string\|Function\|false}`|false| Can be used instead of `template` to provide an inline template - please read the [Writing Your Own Templates](https://github.com/jantimon/html-webpack-plugin#writing-your-own-templates) section |
138
139
  |**`templateParameters`**|`{Boolean\|Object\|Function}`| `false`| Allows to overwrite the parameters used in the template - see [example](https://github.com/jantimon/html-webpack-plugin/tree/master/examples/template-parameters) |
139
140
  |**`inject`**|`{Boolean\|String}`|`true`|`true \|\| 'head' \|\| 'body' \|\| false` Inject all assets into the given `template` or `templateContent`. When passing `true` or `'body'` all javascript resources will be placed at the bottom of the body element. `'head'` will place the scripts in the head element - see the [inject:false example](https://github.com/jantimon/html-webpack-plugin/tree/master/examples/custom-insertion-position)|
141
+ |**`publicPath`**|`{String|'auto'}`|`'auto'`|The publicPath used for script and link tags|
140
142
  |**`scriptLoading`**|`{'blocking'\|'defer'}`|`'blocking'`| Modern browsers support non blocking javascript loading (`'defer'`) to improve the page startup performance. |
141
143
  |**`favicon`**|`{String}`|``|Adds the given favicon path to the output HTML|
142
144
  |**`meta`**|`{Object}`|`{}`|Allows to inject `meta`-tags. E.g. `meta: {viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no'}`|
@@ -146,7 +148,7 @@ Allowed values are as follows
146
148
  |**`cache`**|`{Boolean}`|`true`|Emit the file only if it was changed|
147
149
  |**`showErrors`**|`{Boolean}`|`true`|Errors details will be written into the HTML page|
148
150
  |**`chunks`**|`{?}`|`?`|Allows you to add only some chunks (e.g only the unit-test chunk)|
149
- |**[`chunksSortMode`](#plugins)**|`{String\|Function}`|`auto`|Allows to control how chunks should be sorted before they are included to the HTML. Allowed values are `'none' \| 'auto' \| 'manual' \| {Function}`|
151
+ |**`chunksSortMode`**|`{String\|Function}`|`auto`|Allows to control how chunks should be sorted before they are included to the HTML. Allowed values are `'none' \| 'auto' \| 'manual' \| {Function}`|
150
152
  |**`excludeChunks`**|`{Array.<string>}`|``|Allows you to skip some chunks (e.g don't add the unit-test chunk)|
151
153
  |**`xhtml`**|`{Boolean}`|`false`|If `true` render the `link` tags as self-closing (XHTML compliant)|
152
154
 
package/index.js CHANGED
@@ -27,6 +27,8 @@ const getHtmlWebpackPluginHooks = require('./lib/hooks.js').getHtmlWebpackPlugin
27
27
  const fsStatAsync = promisify(fs.stat);
28
28
  const fsReadFileAsync = promisify(fs.readFile);
29
29
 
30
+ const webpackMajorVersion = Number(require('webpack/package.json').version.split('.')[0]);
31
+
30
32
  class HtmlWebpackPlugin {
31
33
  /**
32
34
  * @param {HtmlWebpackOptions} [options]
@@ -42,6 +44,7 @@ class HtmlWebpackPlugin {
42
44
  templateContent: false,
43
45
  templateParameters: templateParametersGenerator,
44
46
  filename: 'index.html',
47
+ publicPath: userOptions.publicPath === undefined ? 'auto' : userOptions.publicPath,
45
48
  hash: false,
46
49
  inject: userOptions.scriptLoading !== 'defer' ? 'body' : 'head',
47
50
  scriptLoading: 'blocking',
@@ -149,19 +152,23 @@ class HtmlWebpackPlugin {
149
152
  compilation.errors.push(prettyError(templateResult.error, compiler.context).toString());
150
153
  }
151
154
 
152
- const childCompilationOutputName = compilation.mainTemplate.getAssetPath(this.options.filename, 'compiledEntry' in templateResult ? {
155
+ const compiledEntries = 'compiledEntry' in templateResult ? {
153
156
  hash: templateResult.compiledEntry.hash,
154
157
  chunk: templateResult.compiledEntry.entry
155
158
  } : {
156
159
  hash: templateResult.mainCompilationHash
157
- });
160
+ };
161
+
162
+ const childCompilationOutputName = webpackMajorVersion === 4
163
+ ? compilation.mainTemplate.getAssetPath(this.options.filename, compiledEntries)
164
+ : compilation.getAssetPath(this.options.filename, compiledEntries);
158
165
 
159
166
  // If the child compilation was not executed during a previous main compile run
160
167
  // it is a cached result
161
168
  const isCompilationCached = templateResult.mainCompilationHash !== compilation.hash;
162
169
 
163
170
  // Turn the entry point names into file paths
164
- const assets = self.htmlWebpackPluginAssets(compilation, childCompilationOutputName, sortedEntryNames);
171
+ const assets = self.htmlWebpackPluginAssets(compilation, childCompilationOutputName, sortedEntryNames, this.options.publicPath);
165
172
 
166
173
  // If the template and the assets did not change we don't have to emit the html
167
174
  const assetJson = JSON.stringify(self.getAssetFiles(assets));
@@ -201,7 +208,7 @@ class HtmlWebpackPlugin {
201
208
  plugin: self
202
209
  }))
203
210
  .then(({ assetTags }) => {
204
- // Inject scripts to body unless it set explictly to head
211
+ // Inject scripts to body unless it set explicitly to head
205
212
  const scriptTarget = self.options.inject === 'head' ? 'head' : 'body';
206
213
  // Group assets to `head` and `body` tag arrays
207
214
  const assetGroups = this.generateAssetGroups(assetTags, scriptTarget);
@@ -214,7 +221,7 @@ class HtmlWebpackPlugin {
214
221
  });
215
222
  });
216
223
 
217
- // Turn the compiled tempalte into a nodejs function or into a nodejs string
224
+ // Turn the compiled template into a nodejs function or into a nodejs string
218
225
  const templateEvaluationPromise = Promise.resolve()
219
226
  .then(() => {
220
227
  if ('error' in templateResult) {
@@ -306,7 +313,7 @@ class HtmlWebpackPlugin {
306
313
  // To extract the result during the evaluation this part has to be removed.
307
314
  source = source.replace('var HTML_WEBPACK_PLUGIN_RESULT =', '');
308
315
  const template = this.options.template.replace(/^.+!/, '').replace(/\?.+$/, '');
309
- const vmContext = vm.createContext(_.extend({ HTML_WEBPACK_PLUGIN: true, require: require }, global));
316
+ const vmContext = vm.createContext(_.extend({ HTML_WEBPACK_PLUGIN: true, require: require, console: console }, global));
310
317
  const vmScript = new vm.Script(source, { filename: template });
311
318
  // Evaluate code and cast to string
312
319
  let newSource;
@@ -513,6 +520,7 @@ class HtmlWebpackPlugin {
513
520
  * for all given entry names
514
521
  * @param {WebpackCompilation} compilation
515
522
  * @param {string[]} entryNames
523
+ * @param {string | 'auto'} customPublicPath
516
524
  * @returns {{
517
525
  publicPath: string,
518
526
  js: Array<string>,
@@ -521,22 +529,34 @@ class HtmlWebpackPlugin {
521
529
  favicon?: string
522
530
  }}
523
531
  */
524
- htmlWebpackPluginAssets (compilation, childCompilationOutputName, entryNames) {
532
+ htmlWebpackPluginAssets (compilation, childCompilationOutputName, entryNames, customPublicPath) {
525
533
  const compilationHash = compilation.hash;
526
534
 
527
535
  /**
528
536
  * @type {string} the configured public path to the asset root
529
537
  * if a path publicPath is set in the current webpack config use it otherwise
530
- * fallback to a realtive path
538
+ * fallback to a relative path
531
539
  */
532
- const webpackPublicPath = compilation.mainTemplate.getPublicPath({ hash: compilationHash });
533
- const isPublicPathDefined = webpackPublicPath.trim() !== '';
534
- let publicPath = isPublicPathDefined
535
- // If a hard coded public path exists use it
536
- ? webpackPublicPath
537
- // If no public path was set get a relative url path
538
- : path.relative(path.resolve(compilation.options.output.path, path.dirname(childCompilationOutputName)), compilation.options.output.path)
539
- .split(path.sep).join('/');
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
+ // Webpack 5 introduced "auto" - however it can not be retrieved at runtime
547
+ : webpackPublicPath.trim() !== '' && webpackPublicPath !== 'auto';
548
+
549
+ let publicPath =
550
+ // If the html-webpack-plugin options contain a custom public path uset it
551
+ customPublicPath !== 'auto'
552
+ ? customPublicPath
553
+ : (isPublicPathDefined
554
+ // If a hard coded public path exists use it
555
+ ? webpackPublicPath
556
+ // If no public path was set get a relative url path
557
+ : path.relative(path.resolve(compilation.options.output.path, path.dirname(childCompilationOutputName)), compilation.options.output.path)
558
+ .split(path.sep).join('/')
559
+ );
540
560
 
541
561
  if (publicPath.length && publicPath.substr(-1, 1) !== '/') {
542
562
  publicPath += '/';
@@ -585,7 +605,7 @@ class HtmlWebpackPlugin {
585
605
  if (!asset) {
586
606
  return true;
587
607
  }
588
- // Prevent hot-module files from beeing included:
608
+ // Prevent hot-module files from being included:
589
609
  const assetMetaInformation = asset.info || {};
590
610
  return !(assetMetaInformation.hotModuleReplacement || assetMetaInformation.development);
591
611
  });
@@ -622,8 +642,8 @@ class HtmlWebpackPlugin {
622
642
  }
623
643
 
624
644
  /**
625
- * Converts a favicon file from disk to a webpack ressource
626
- * and returns the url to the ressource
645
+ * Converts a favicon file from disk to a webpack resource
646
+ * and returns the url to the resource
627
647
  *
628
648
  * @param {string|false} faviconFilePath
629
649
  * @param {WebpackCompilation} compilation
@@ -58,7 +58,7 @@ class CachedChildCompilation {
58
58
  * @type {WebpackCompiler}
59
59
  */
60
60
  this.compiler = compiler;
61
- // Create a singlton instance for the compiler
61
+ // Create a singleton instance for the compiler
62
62
  // if there is none
63
63
  if (compilerMap.has(compiler)) {
64
64
  return;
@@ -18,8 +18,8 @@ const LibraryTemplatePlugin = require('webpack/lib/LibraryTemplatePlugin');
18
18
  const SingleEntryPlugin = require('webpack/lib/SingleEntryPlugin');
19
19
 
20
20
  /**
21
- * The HtmlWebpackChildCompiler is a helper to allow resusing one childCompiler
22
- * for multile HtmlWebpackPlugin instances to improve the compilation performance.
21
+ * The HtmlWebpackChildCompiler is a helper to allow reusing one childCompiler
22
+ * for multiple HtmlWebpackPlugin instances to improve the compilation performance.
23
23
  */
24
24
  class HtmlWebpackChildCompiler {
25
25
  /**
@@ -53,14 +53,14 @@ class HtmlWebpackChildCompiler {
53
53
 
54
54
  /**
55
55
  * Returns true if the childCompiler is currently compiling
56
- * @retuns {boolean}
56
+ * @returns {boolean}
57
57
  */
58
58
  isCompiling () {
59
59
  return !this.didCompile() && this.compilationStartedTimestamp !== undefined;
60
60
  }
61
61
 
62
62
  /**
63
- * Returns true if the childCOmpiler is done compiling
63
+ * Returns true if the childCompiler is done compiling
64
64
  */
65
65
  didCompile () {
66
66
  return this.compilationEndedTimestamp !== undefined;
@@ -118,7 +118,16 @@ class HtmlWebpackChildCompiler {
118
118
  }
119
119
  // Reject the promise if the childCompilation contains error
120
120
  if (childCompilation && childCompilation.errors && childCompilation.errors.length) {
121
- const errorDetails = childCompilation.errors.map(error => error.message + (error.error ? ':\n' + error.error : '')).join('\n');
121
+ const errorDetails = childCompilation.errors.map(error => {
122
+ let message = error.message;
123
+ if (error.error) {
124
+ message += ':\n' + error.error;
125
+ }
126
+ if (error.stack) {
127
+ message += '\n' + error.stack;
128
+ }
129
+ return message;
130
+ }).join('\n');
122
131
  reject(new Error('Child compilation failed:\n' + errorDetails));
123
132
  return;
124
133
  }
@@ -159,12 +168,18 @@ class HtmlWebpackChildCompiler {
159
168
  * @returns Array<string>
160
169
  */
161
170
  function extractHelperFilesFromCompilation (mainCompilation, childCompilation, filename, childEntryChunks) {
171
+ const webpackMajorVersion = Number(require('webpack/package.json').version.split('.')[0]);
172
+
162
173
  const helperAssetNames = childEntryChunks.map((entryChunk, index) => {
163
- return mainCompilation.mainTemplate.getAssetPath(filename, {
174
+ const entryConfig = {
164
175
  hash: childCompilation.hash,
165
176
  chunk: entryChunk,
166
177
  name: `HtmlWebpackPlugin_${index}`
167
- });
178
+ };
179
+
180
+ return webpackMajorVersion === 4
181
+ ? mainCompilation.mainTemplate.getAssetPath(filename, entryConfig)
182
+ : mainCompilation.getAssetPath(filename, entryConfig);
168
183
  });
169
184
 
170
185
  helperAssetNames.forEach((helperFileName) => {
@@ -1,6 +1,6 @@
1
1
  // @ts-check
2
2
  /**
3
- * To use the availble webpack core api
3
+ * To use the available webpack core api
4
4
  * we have to use different child compilers
5
5
  * depending on the used webpack version
6
6
  */
package/lib/html-tags.js CHANGED
@@ -2,8 +2,8 @@
2
2
  /** @typedef {import("../typings").HtmlTagObject} HtmlTagObject */
3
3
  /**
4
4
  * @file
5
- * This file provides to helper to create html as a object repesentation as
6
- * thoses objects are easier to modify than pure string representations
5
+ * This file provides to helper to create html as a object representation as
6
+ * those objects are easier to modify than pure string representations
7
7
  *
8
8
  * Usage:
9
9
  * ```
@@ -47,7 +47,7 @@ function htmlTagObjectToString (tagDefinition, xhtml) {
47
47
  * Static helper to create a tag object to be get injected into the dom
48
48
  *
49
49
  * @param {string} tagName
50
- * the name of the tage e.g. 'div'
50
+ * the name of the tag e.g. 'div'
51
51
  *
52
52
  * @param {{[attributeName: string]: string|boolean}} [attributes]
53
53
  * tag attributes e.g. `{ 'class': 'example', disabled: true }`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "html-webpack-plugin",
3
- "version": "4.2.2",
3
+ "version": "4.5.0",
4
4
  "license": "MIT",
5
5
  "description": "Simplifies creation of HTML files to serve your webpack bundles",
6
6
  "author": "Jan Nicklas <j.nicklas@me.com> (https://github.com/jantimon)",
@@ -61,7 +61,7 @@
61
61
  "util.promisify": "1.0.0"
62
62
  },
63
63
  "peerDependencies": {
64
- "webpack": ">=4.0.0 < 6.0.0"
64
+ "webpack": "^4.0.0 || ^5.0.0"
65
65
  },
66
66
  "keywords": [
67
67
  "webpack",
package/typings.d.ts CHANGED
@@ -10,6 +10,17 @@ declare class HtmlWebpackPlugin {
10
10
  apply(compiler: Compiler): void;
11
11
 
12
12
  static getHooks(compilation: compilation.Compilation): HtmlWebpackPlugin.Hooks;
13
+
14
+ /**
15
+ * Static helper to create a tag object to be get injected into the dom
16
+ */
17
+ static createHtmlTagObject(
18
+ tagName: string,
19
+ attributes?: { [attributeName: string]: string | boolean },
20
+ innerHTML?: string
21
+ ): HtmlWebpackPlugin.HtmlTagObject;
22
+
23
+ static readonly version: number;
13
24
  }
14
25
 
15
26
  declare namespace HtmlWebpackPlugin {
@@ -23,7 +34,7 @@ declare namespace HtmlWebpackPlugin {
23
34
  interface ProcessedOptions {
24
35
  /**
25
36
  * Emit the file only if it was changed.
26
- * Default: `true`.
37
+ * @default true
27
38
  */
28
39
  cache: boolean;
29
40
  /**
@@ -32,14 +43,14 @@ declare namespace HtmlWebpackPlugin {
32
43
  chunks: "all" | string[];
33
44
  /**
34
45
  * Allows to control how chunks should be sorted before they are included to the html.
35
- * Default: `'auto'`.
46
+ * @default 'auto'
36
47
  */
37
48
  chunksSortMode:
38
49
  | "auto"
39
50
  | "manual"
40
51
  | (((entryNameA: string, entryNameB: string) => number));
41
52
  /**
42
- * List all entries which should not be injeccted
53
+ * List all entries which should not be injected
43
54
  */
44
55
  excludeChunks: string[];
45
56
  /**
@@ -48,10 +59,15 @@ declare namespace HtmlWebpackPlugin {
48
59
  favicon: false | string;
49
60
  /**
50
61
  * The file to write the HTML to.
51
- * Defaults to `index.html`.
52
62
  * Supports subdirectories eg: `assets/admin.html`
63
+ * @default 'index.html'
53
64
  */
54
65
  filename: string;
66
+ /**
67
+ * By default the public path is set to `auto` - that way the html-webpack-plugin will try
68
+ * to set the publicPath according to the current filename and the webpack publicPath setting
69
+ */
70
+ publicPath: string | 'auto';
55
71
  /**
56
72
  * If `true` then append a unique `webpack` compilation hash to all included scripts and CSS files.
57
73
  * This is useful for cache busting
@@ -70,7 +86,7 @@ declare namespace HtmlWebpackPlugin {
70
86
  * blocking will result in <script src="..."></script>
71
87
  * defer will result in <script defer src="..."></script>
72
88
  *
73
- * The default behaviour is blocking
89
+ * @default 'blocking'
74
90
  */
75
91
  scriptLoading:
76
92
  | "blocking"
@@ -87,11 +103,11 @@ declare namespace HtmlWebpackPlugin {
87
103
  | { [attributeName: string]: string | boolean }; // custom properties e.g. { name:"viewport" content:"width=500, initial-scale=1" }
88
104
  };
89
105
  /**
90
- * HTML Minification options accepts the following valeus:
106
+ * HTML Minification options accepts the following values:
91
107
  * - Set to `false` to disable minifcation
92
108
  * - Set to `'auto'` to enable minifcation only for production mode
93
109
  * - Set to custom minification according to
94
- * @https://github.com/kangax/html-minifier#options-quick-reference
110
+ * {@link https://github.com/kangax/html-minifier#options-quick-reference}
95
111
  */
96
112
  minify: 'auto' | boolean | MinifyOptions;
97
113
  /**