Html-webpack-plugin: webpack 5 <-> html-webpack-plugin 5

Created on 13 Oct 2020  ·  126Comments  ·  Source: jantimon/html-webpack-plugin

Finally Webpack 5 has been released! 👍

During the beta I tried to provide a html-webpack-plugin version which is compatible to webpack 4 and webpack 5.
As there have been some API and typing changes in webpack 5 this approach is limited.

To provide the best possible webpack 5 support I have started on a dedicated webpack 5 version of the html-webpack-plugin.

current progress:

  • [x] drop webpack 4 support
  • [x] drop node < 10 like webpack
  • [x] make use of Compiler.hook.initialize to get the latest options
  • [x] update typings for webpack 5
  • [x] fix scriptLoading defer for inject false
  • [x] make scriptLoading defer the default
  • [x] add assets in Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL (see https://github.com/webpack/webpack/issues/11425#issuecomment-686606318 )
  • [x] add assets with new api compilation.emitAsset (#1522)
  • [x] use new webpack.sources.RawSource(html) to create assets
  • [x] add support for [name]
  • [x] provide options and output name in all hooks
  • [x] allow filename to be a function
  • [x] emitAssets even if they have been generated in a previous compilation (to fix #1476 and #1432)
  • [x] use compiler.webpack.LibraryTemplatePlugin
  • [x] verify support for raw-loader (blocked by https://github.com/webpack/webpack/issues/11909)
  • [x] remove @types/tapable as it is included in tapable 2
  • [x] provide a publicPath to the child compiler to add support for publicPath: 'auto' & 'asset/resource' (https://github.com/webpack/webpack/issues/11968#issuecomment-725117719)
  • [x] use the correct stage to allow sri and service worker generation (blocked by https://github.com/webpack/webpack/issues/11822)
  • [x] fix error reporting (which is currently breaking the travis build)
  • [x] use the html-webpack-plugin publicPath option also for the template child compilation

  • remove html-minification (if a separate plugin which covers the html minification is available) (postponed)

current blockers (help needed by the webpack team):

current alpha playround:

CodeSandbox of the html-webpack-plugin 5.0.0-alpha.17 html-webpack-plugin_5_x_alpha_-_CodeSandbox

Most of the work is done just by me in my spare time for fun - so if this work helps you feel free to buy me a beer 🍺

Most helpful comment

It looks like everything works well so I will release html-webpack-plugin 5.x as a stable release soon

All 126 comments

FWIW, webpack v4.40.0 added the new Asset API, so you may not have to drop webpack v4.x support completely, if you require that users update to at least that version.

(It's still pretty inconvenient to have to hook into the compilation in two fundamentally different ways, depending on whether you're using webpack v4.x or webpack v5.x, though.)

good news, waiting 👍

and When is it expected to be released?

@jeffposnick I have an idea to fix your issue - can you please try the next branch?

Instead of extracting the result of the child compiler it will now extract the assets inside a child compiler hook:

const extractedAssets = [];
      childCompiler.hooks.compilation.tap('HtmlWebpackPlugin', (compilation) => {
        compilation.hooks.processAssets.tap(
          {
            name: 'HtmlWebpackPlugin',
            stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
          },
          (assets) => {
            temporaryTemplateNames.forEach((temporaryTemplateName) => {
              if (assets[temporaryTemplateName]) {
                extractedAssets.push(assets[temporaryTemplateName]);
                compilation.deleteAsset(temporaryTemplateName);
              }
            });
          }
        );
      });

@tianyingchun hard to say - depends a little bit on my time :)

I'm seeing different behavior, but not having luck getting access to the assets created by html-webpack-plugin from within my plugin yet. I'm using the following devDependencies:

"html-webpack-plugin": "github:jantimon/html-webpack-plugin#next",
"webpack": "webpack@^5.1.0"

First off, I see the following originating from html-webpack-plugin:

(node:79288) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning: Compilation.assets will be frozen in future, all modifications are deprecated.
BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.
        Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.
        Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.

And at the time my plugin runs, I don't see the expected index.html in either the main compilation's assets, or the child compilation's assets. (So this part is different in the next branch, as I was previously seeing the incorrectly named index.html in the child compilation's assets.)

I am curious as to whether you really need to go through the steps of deleting your assets from the child compilation and adding them to the parent compilation—maybe someone from the webpack team could weigh in on the best practice? There is a mode in the plugin that I support in which a child compilation is performed (independent of the logic related to getting a list of all the assets), and I just leave the assets it creates as part of the child compilation, and don't attempt to "move" them to the parent compilation.

My plugin, at least, already iterates over both the parent and any child compilations to get the asset list from each.

💯 My projects totally want to upgrade to webpack@5 exception html-webpack-plugin cause of i have some cusomized html plugin based on the hooks of html-webpack-plugin if you have ready for html-webpack-plugin@next i can install as devDeps to do some testings works. :)

@jeffposnick okay good to know that the temporary file disappeared - now I just need to use the same api to add it once again.

Deleting the compiled template from the child compilation as it will be processed even further before it is added again with the final name. It also allows to compile a template only once even if it is used to generate multiple html files.

There seems to be a blocker - if I move the asset additions away from the emit phase the child compilation is not done.

I pushed the current version as [email protected] which you should be able to install with html-webpack-plugin@next

Wow @sokra improved the deleteAsset function https://github.com/webpack/webpack/pull/11704 so now we can use thisCompilation for the child compiler. 👍

I have just released [email protected] (which requires webpack 5.1.2) - it is now adding the assets the right way @jeffposnick could you please try it once again?

@jantimon
i tried [email protected] & [email protected] it also throw error

(node:48122) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning: Compilation.assets will be frozen in future, all modifications are deprecated.
BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.
        Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.
        Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.
TypeError: The 'compilation' argument must be an instance of Compilation

Thanks for testing @tianyingchun - it looks like this release didn't include all changes - can you please try one more time with Now it's part of [email protected] ?

Thanks for testing @tianyingchun - it looks like this release didn't include all changes - can you please try one more time with Now it's part of [email protected] ?

I don't have this problem anymore. Well done 👍

@jantimon yes the [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning has disappeared. but have another questions about the hooks of html-webpack-plugin i write a plugin based on the hooks thisCompilation as bellow

apply(compiler: Compiler): void { 
    compiler.hooks.thisCompilation.tap(this.pluginName, (compilation) => {
      compilation.mainTemplate.hooks.requireExtensions.tap(this.pluginName, () => {
....

finnally it give an error

TypeError: The 'compilation' argument must be an instance of Compilation

@tianyingchun I am not sure how this would be connected to the html-webpack-plugin.. if it is could you please open a new issue for that part?

ok, i will research this issue first, thanks very much. 👍

alpha-5 still can not success build it throws error like https://github.com/jantimon/html-webpack-plugin/issues/1451

alpha.6 is working fine with my simple webconfig. I say simple since 4.5.0 also was working while using webpack 5

@jantimon Hi looks like in v5.alpha.6, favicon is breaking. This is my repo. My case is that I have a favicon.ico file of around 14kb, when I do yarn build I can see it gets emitted to favicon.ico of 27kb, and this icon is clearly corrupted.

This works fine for 5.alpha.6, the favicon emitted is 14kb and works just fine.

@akphi we convert the favicon into a RawSource - maybe that's wrong:

https://github.com/jantimon/html-webpack-plugin/blob/1696eff5c0c029fecb9bd3f9efbf1c2a81857aa4/index.js#L467

Can you please try to find out if there is a better way to add binary files to the webpack compilation?

@jantimon I just went through the code for RawSource.

From the list they have in webpack-sources, not sure if I could suggest a better one. But, why do we set convertToString=true here?

https://github.com/jantimon/html-webpack-plugin/blob/1696eff5c0c029fecb9bd3f9efbf1c2a81857aa4/index.js#L467

I couldn't find any API documentation about the best usage and tried true

Can you please try to change it to false locally? Maybe it works better that way for binary files

@jantimon sure, I mean, the doc is sorta outdated as well, but if it's binary I think we can treat it as buffer. Can you teach me how to get compile and use this plugin locally for my project? Glad to help!

You don't have to compile anything just play around with node_modules/html-webpack-plugin/index.js

E.g. try to add a console.log statement :)

Just note that if you are using webpack-dev-server you will have to restart it in order to see any changes.

@jantimon yep, changing it to false works for me. Looks like addFileToAssets is only being used for favicon right now so it's probably safe to make this change. But my use case is utterly the most basic use case of this plugin, we probably should check with other folks who have more advanced use cases to see if this makes sense.

Cool 👍 can you please create a pull request?

@jantimon do you want to expose the convertAsString flag as param for addFileToAssets or we just default it to false for now?

not for now - if we will see that it causes any issue we can still add it

just set it to false

@akphi released as [email protected]

When I run webpack with the --watch parameter, index.html file is not being generated. The version is 5.0.0-alpha.7.

@dstarosta are you using the clean-webpack-plugin ?

@jantimon Yes. I found that the cache: false option fixes the problem.

Cool I also added it to the todo list for the next major

@jantimon: here's what I've found so far as I've tried upgrading to webpack5:

For reference sake, here's my html-webpack-plugin config:

    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'src', 'views', 'index-template.html'),
      chunks: ['main'],
      inject: 'body',
      alwaysWriteToDisk: true,
      filename: 'index.html',
    }),
    new HtmlWebpackHarddiskPlugin({
      outputPath: path.resolve(__dirname, 'src', 'views'),
    }),

here's my (simplified) html template:

<!DOCTYPE html>
<html lang="en-us">
  <head>
    <meta charset="utf-8" />
  </head>
  <body>
    <div id="root" style="height: 100%"></div>
  </body>
</html>

and here's what I generally expect my html file to look like:

<!DOCTYPE html>
<html lang="en-us">
  <head>
    <meta charset="utf-8" />
    <link href="/public/main.f44825e38502163de35f.css" rel="stylesheet" />
  </head>
  <body>
    <div id="root></div>
    <script src="/public/client.bundle.main.b6f9288ceaebb62ab9b6.js"></script>
  </body>
</html>
  1. first, we were on [email protected] -- it actually seems to _work_ just fine for us, although webpack 5 complains about a breaking change: (node:33423) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning: Compilation.assets will be frozen in future, all modifications are deprecated. BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation. Do changes to assets earlier, e. g. in Compilation.hooks.processAssets. Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.
  2. then I tried updating to [email protected] -- it doesn't work, as it writes the wrong bundle file to my html template (it writes the wrong hash) -- from my config: filename: 'client.bundle.[name].[contenthash].js',. Otherwise, the html is fine.
  3. Beginning with [email protected] and continuing to alpha.10, it seems to ignore my html template entirely. Here's an example of what actually gets written to my index.html file (note use strict getting written as content, which I assume is some incomplete portion of a bundle):
<head>
  <link href="/public/main.9dbd8023185a251ff841.css" rel="stylesheet" /></head
>use strict
<script
  defer="defer"
  src="/public/client.bundle.main.7e131d3de7998ab8c3c8.js"
></script>

@jrnail23 thanks for the detailed error report

I created a CodeSandbox of the html-webpack-plugin 5.0.0-alpha.10 html-webpack-plugin_5_x_alpha_-_CodeSandbox

Can you please create a fork and try to reproduce the errors you describe?

I don't know, @jantimon, I feel pretty disrespected, what with you making me wait 14 whole minutes for a reply! (seriously kidding -- _thanks for the really quick response_!).
I'll see what I can do with it.

Your second point is really a big problem - the html-webpack-plugin injects the css & js before those files are being optimized

This was necessary to work around the deprecation message..

However in this compilation stage we don't know the final filename

In order to properly resolve that issue we need support from @sokra so I created an issue to find a better compilation stage here:
https://github.com/webpack/webpack/issues/11822

Before that blocker is resolved we will probably not be able to release a stable html-webpack-plugin 5.x version

@jantimon: so one thing I guess I left out: everything is fine when I run in watch mode, using devServer.
My problems only occur when I run webpack CLI, in non-watch mode (production vs. development mode doesn't seem to matter).

I get what you're saying about the post-optimization issue... might that by chance be fixable via Webpack 5's new "true content hashing" (which, AFAICT, is intended to make contenthash reflect the source file content)?

Otherwise in the meantime, is there any indication that v4.5 is unsafe, despite the "breaking change" message?

All unit tests are passing for 4.5 however I am not sure if it will work with future webpack 5 releases as it relies on a from now on unsupported webpack api

4.5 has also some issues with webpack 5s new singleton hook system.. so it will probably break if you have multiple webpack versions installed

@jantimon, I wanted to draw your attention to this statement, which I added on after the fact:

My problems only occur when I run webpack CLI, in non-watch mode (production vs. development mode doesn't seem to matter).

Any thoughts on why it's (seemingly) bypassing my template in non-watch mode?

Here is a working example with [email protected]:

webpack.zip

npm run webpack

@jantimon, thanks, I'll take a look

@jantimon OK, I think I finally have something useful for you here.
Sorry these details have to drip out one at a time instead of giving you all the relevant stuff up front -- in trying not to throw the whole kitchen sink at you (and also to protect my employer's code), I oversimplified my examples.

We use express-es6-template-engine for our html pages.

Those files are saved as html files, and their content looks something like this (note the es6 template literal variable ${myTitle} for <title>):

<!DOCTYPE html>
<html lang="en-us">
  <head>
    <meta charset="utf-8" />
    <title>${myTitle}</title>
  </head>
  <body>
    <div id="root" style="height: 100%"></div>
  </body>
</html>

So my expected html file should look something like this (our express templating engine deals with that myTitle variable later, when it serves the page):

<!DOCTYPE html>
<html lang="en-us">
  <head>
    <meta charset="utf-8" />
    <title>${myTitle}</title>
  </head>
  <body>
    <div id="root" style="height: 100%"></div>
    <script defer="defer" src="main.js"></script>
  </body>
</html>

Since we end up including an html file in our output, we also add the following to our webpack config:

  module: {
    rules: [
      {
        test: /\.(html)$/,
        use: ['raw-loader'],
      },
    ]
  },

Now when I run webpack, I get the following in my dist/index.html file:

use strict<script defer="defer" src="main.js"></script>

Here is a minimal example:
webpack.zip

It seems like raw-loader is not playing nicely with html-webpack-plugin. When I remove it, I get the correct output, but with it, I get the use strict output. I tried removing the raw-loader rule in my actual project as well, and it no longer has the use strict screwiness. It does, however, still have the wrong bundle hash, per the issue you already know about.

@jrnail23 thanks it looks like the new webpack 5 child compiler is configured in a wrong way or buggy - I created a new issue here: https://github.com/webpack/webpack/issues/11909

I'm glad you were able to make some sense of that. Thank you!

5.0.0-beta.11's typings.d.ts appears to be broken:

node_modules/html-webpack-plugin/typings.d.ts:36:13 - error TS2430: Interface 'Options' incorrectly extends interface 'Partial<ProcessedOptions>'.
  Types of property 'filename' are incompatible.
    Type 'string | ((entryName: string) => string) | undefined' is not assignable to type 'string | undefined'.
      Type '(entryName: string) => string' is not assignable to type 'string'.

36   interface Options extends Partial<ProcessedOptions> {

EDIT: fixed in beta.12

Thanks @AviVahl I'll take a look

Hi @jantimon

Can I ask why are we hooking into after this stage PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE instead of PROCESS_ASSETS_STAGE_OPTIMIZE_HASH? So that if filename uses contenthash it will be reflected in the html?

      compilation.hooks.processAssets.tapAsync(
        {
          name: 'HtmlWebpackPlugin',
          stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
          stage:
          /**
           * Hacky intermediate solution arround the open webpack issue https://github.com/webpack/webpack/issues/11822 which does not
           * allow to generate the HTML after the JS and CSS has been optimized
           *
           * This can break on any minor webpack release as it messes with the webpack internal enum values:
          */
          webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE + 200

https://github.com/jantimon/html-webpack-plugin/commit/73cb5f6d9f1b291786051f381dbc0ae2439802cd#diff-e727e4bdf3657fd1d798edcd6b099d6e092f8573cba266154583a746bba0f346R217

Thanks @phungtuanhoang1996 for your feedback
You are right the html-webpack-plugin 5.x is not using the perfect timing to add the html assets

I couldn't find PROCESS_ASSETS_STAGE_OPTIMIZE_HASH in the official documentation: https://webpack.js.org/api/compilation-hooks/#additionalassets - is it save to be used?

In order to properly resolve that issue I also reached out to the webpack core team and created an issue to find a better compilation stage: https://github.com/webpack/webpack/issues/11822

@sokra has already started working on this topic and created a pull request https://github.com/webpack/webpack/pull/11956 to add a processAdditionalAssets assets stage but I still need to find out how it should be used in the optimal way - if you have any ideas please let me know

@jantimon I think the webpack team did not update the documentation. I was looking at [email protected] source code and the optimize hash stage is there
https://github.com/webpack/webpack/blob/84dafd164499b6080243cf9d00537b47b6e075c2/lib/Compilation.js#L3476

@phungtuanhoang1996 I released 5.0.0-alpha.14 with PROCESS_ASSETS_STAGE_OPTIMIZE_HASH but as mentioned in https://github.com/jantimon/html-webpack-plugin/issues/1527#issuecomment-724543871 this will be only a intermediate solution

Hi @jantimon l use the version of [email protected] and this error appears "ERROR in Conflict: Multiple assets emit different content to the same filename index.html". What's going on? I use index.ejs no problem.

Here's how to use it

    new HtmlWebpackPlugin({
      favicon: resolveDirname("./public/favicon.ico"),
      template: resolveDirname("./public/index.html")
    }),

Can you please try to reproduce that bug in the following sandbox and save it as a fork?

https://codesandbox.io/s/html-webpack-plugin-5x-alpha-d37s2?file=/webpack.config.js

Can you please try to reproduce that bug in the following sandbox and save it as a fork?

https://codesandbox.io/s/html-webpack-plugin-5x-alpha-d37s2?file=/webpack.config.js

I can’t reproduce using this sandbox.
You can clone this repository for testing.
https://github.com/1247748612/htmlWebpackPluginDemo

Sorry your repository has too many different npm packages, abstractions, plugins and logic which makes it very time consuming task to debug..

Sorry your repository has too many different npm packages, abstractions, plugins and logic which makes it very time consuming task to debug..

Thanks you. I know, but only then did it cause an error. I use html-webpack-plugin version 4 and it does not cause this bug.

I am only guessing but it might be because of the VueLoaderPlugin().
Can you please try to remove it and let me know if the error is still occurring?

I am only guessing but it might be because of the VueLoaderPlugin().
Can you please try to remove it and let me know if the error is still occurring?

I tried to delete some plugins, then tested and found the reason. This is caused by copy-webpack-plugin because it uses the folder containing index.html. html-webpack-plugin uses index.html.

I am only guessing but it might be because of the VueLoaderPlugin().
Can you please try to remove it and let me know if the error is still occurring?

This error appears in this sandbox link, you need to run "yarn webpack" or "yarn webpack serve --port 9090" will appear.
https://codesandbox.io/s/html-webpack-plugin-5x-alpha-forked-m1sb4?file=/webpack.config.js

Wow awesome thanks a lot @1247748612 - it's a bug of the copy plugin as it copies the index.html although should be ignored.

Webpack will now get two index.html files one from HtmlWebpackPlugin and one from the CopyPlugin and doesn't know which is the correct one.. therefore the build fails

Can you please move this bug to the CopyPlugin?

Wow awesome thanks a lot @1247748612 - it's a bug of the copy plugin as it copies the index.html although should be ignored.

Webpack will now get two index.html files one from HtmlWebpackPlugin and one from the CopyPlugin and doesn't know which is the correct one.. therefore the build fails

Can you please move this bug to the CopyPlugin?

okay. I have copied it

I still get the DEP_WEBPACK_COMPILATION_ASSETS message.

Tried with:

@sethomas That's probably by one of your other plugins - please remove all other plugins and try again or use https://nodejs.org/api/cli.html#cli_trace_deprecation to find out which plugin is causing it

(node:48122) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning: Compilation.assets will be frozen in future, all modifications are deprecated. BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation. Do changes to assets earlier, e. g. in Compilation.hooks.processAssets. Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.

I can confirm that 5.0.0-alpha.14 resolved the warning above. When can we expect an official release?

@gauravshah27 right now it is blocked by these two issues:

  • webpack/issues/11822
  • webpack/issues/11909

The version 5.0.0-alpha.14 seems to unable to "live-reload" on dev-server with multiple "targets" config.

% npx webpack serve --mode development

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  output: {
    publicPath: '/'
  },
  devServer: {
    contentBase: path.resolve(__dirname, './src'),
    contentBasePublicPath: '/',
    watchContentBase: true,
    hot: true
  },
  target: ['web', 'es5'],
  plugins: [
    new HtmlWebpackPlugin({
      template: './src/index.html'
    })
  ]
};

@yossoon Should be a bug in webpack-dev-server https://github.com/webpack/webpack-dev-server/issues/2758, you can work around it with target: 'web' for development mode until webpack-dev-server v4 is out.

Thank you for telling me @chenxsan ! It looks not the right time to migrate Webpack 4 for a while.

I think another issue with html-webpack-plugin@next is that it still depends on "@types/tapable": "^1.0.5", but tapable is now version 2.1.1 and has its own types and does not depend on @types

thanks @bboydflo I added it to the todo list :)

One blocker around the child compiler has been resolved by the webpack team! :)
I'll try to build a new html-webpack-plugin@next release based on the new child compilation solution soon

Hello. I have an issue with the latest commit from next branch.
Here is the error when I'm trying to build in development mode.

(node:9744) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined
    at Hash.update (internal/crypto/hash.js:84:11)
    at BulkUpdateDecorator.update (C:\Users\tdarneix\Development\centreon-dev-ecosystem-wp5\centreon\node_modules\webpack\lib\util\createHash.js:49:14)
    at NormalModule.updateHash (C:\Users\tdarneix\Development\centreon-dev-ecosystem-wp5\centreon\node_modules\webpack\lib\NormalModule.js:1060:8)
    at Compilation.createModuleHashes (C:\Users\tdarneix\Development\centreon-dev-ecosystem-wp5\centreon\node_modules\webpack\lib\Compilation.js:2726:12)
    at C:\Users\tdarneix\Development\centreon-dev-ecosystem-wp5\centreon\node_modules\webpack\lib\Compilation.js:2064:11
    at Hook.eval [as callAsync] (eval at create (C:\Users\tdarneix\Development\centreon-dev-ecosystem-wp5\centreon\node_modules\webpack\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:6:1)    
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\Users\tdarneix\Development\centreon-dev-ecosystem-wp5\centreon\node_modules\webpack\node_modules\tapable\lib\Hook.js:18:14)
    at C:\Users\tdarneix\Development\centreon-dev-ecosystem-wp5\centreon\node_modules\webpack\lib\Compilation.js:2024:36
    at eval (eval at create (C:\Users\tdarneix\Development\centreon-dev-ecosystem-wp5\centreon\node_modules\webpack\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:11:1)
    at C:\Users\tdarneix\Development\centreon-dev-ecosystem-wp5\centreon\node_modules\html-webpack-plugin\lib\cached-child-compiler.js:237:53

Using the production mode works perfectly.

And here is my configuration about html-webpack-plugin.

new HtmlWebpackPlugin({
    alwaysWriteToDisk: true,
    template: './www/front_src/public/index.html',
    filename: 'index.html',
}),

Apologies if this isn't the right place for this. I'm experimenting with the type: 'asset/resource' field for css files with webpack 5. The CSS files are being emitted correctly, however html-webpack-plugin is not including them in the final HTML file. I tried@next` as well with the same result. Is that just something that is still being worked on or do I need additional configuration for that workflow?

@garand can you please create an example with type: 'asset/resource' on codesandbox?
You can use this box as template: https://codesandbox.io/s/html-webpack-plugin-5x-alpha-d37s2?file=/webpack.config.js

There is an open task already in the intro post - with a link to a possible solution I need to try :)

released [email protected]

  • allows to use raw-loader again (like it used to work in html-webpack-plugin@4)
  • add partial support for type: 'asset/resource' (right now it ignores the html-webpack-public publicPath option)
  • removed @types/tapable (as it is included in tapable 2)

@sokra merged https://github.com/webpack/webpack/pull/11956 which allows to define the timing when html-webpack-plugin runs during the compilation into webpack v5.10.0!

This resolves all current blockers and allows to prepare a html-webpack-plugin beta version!

Current open tasks before a beta can be release:

  • use PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE from https://github.com/webpack/webpack/pull/11956
  • use html-webpack-plugin publicPath option also for the child compilation to allow correct public path includes for images inside the html

Similar problem with https://github.com/jantimon/html-webpack-plugin/issues/1527#issuecomment-738001951. I'm using 5.0.0-alpha.15 and getting The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined error in development mode.

The error stack traces down to the following statement https://github.com/jantimon/html-webpack-plugin/blob/1de31cd85e1a995837cf8986f741d801660ecef1/lib/cached-child-compiler.js#L237

Here's my configuration

new HtmlWebpackPlugin({
  filename: 'index.html',
  template: 'public/index.html',
  templateParameters: {
    version: childProcess.execSync('git rev-parse --short HEAD').toString(),
    publishDate: `${dayjs().format('YYYY-MM-DD HH:mm:ss')}`,
  },
  minify: false,
}),

@SevenOutman can you please create an minimal reproduction example of that bug on codesandbox?
You can use this box as template: https://codesandbox.io/s/html-webpack-plugin-5x-alpha-d37s2?file=/webpack.config.js

@jantimon No idea how to get sandbox to run with my webpack config. Here's my fork of your template. I changed template option to src/index.html but the terminal keeps throwing Can't resolve '/sandbox/src/template.ejs' in '/sandbox' even if I'm not requiring that path.

@SevenOutman your sandbox looks great:
html-webpack-plugin_5_x_alpha__forked__-_CodeSandbox
you have to restart the sandbox from time to time

@jantimon @SevenOutman I don't think this error come from html-webpack-plugin. I have experimented this issue without html-webpack-plugin. I think it is related to webpack

@Thebarda Looks like you're right. The error is gone when I remove importing .svg from my source code.

@SevenOutman What is your loader for SVG file ?

@Thebarda I'm using svg-sprite-loader, installed v5.1.1 directly from GitHub.

@SevenOutman For what it's worth, we're also using svg-sprite-loader version 5.1.1 and are getting this error:

[webpack-cli] TypeError: Cannot read property 'outputPath' of undefined
    at SVGSpritePlugin.apply (C:\sources_git\strata\applications\alabaster\ui\node_modules\svg-sprite-loader\lib\plugin.js:64:29)
    at createCompiler (C:\sources_git\strata\applications\alabaster\ui\node_modules\webpack\lib\webpack.js:69:12)
    at create (C:\sources_git\strata\applications\alabaster\ui\node_modules\webpack\lib\webpack.js:113:15)
    at webpack (C:\sources_git\strata\applications\alabaster\ui\node_modules\webpack\lib\webpack.js:121:46)
    at f (C:\sources_git\strata\applications\alabaster\ui\node_modules\webpack\lib\index.js:35:15)
    at WebpackCLI.createCompiler (C:\sources_git\strata\applications\alabaster\ui\node_modules\webpack-cli\lib\webpack-cli.js:176:24)
    at WebpackCLI.run (C:\sources_git\strata\applications\alabaster\ui\node_modules\webpack-cli\lib\webpack-cli.js:268:25)
    at async runCLI (C:\sources_git\strata\applications\alabaster\ui\node_modules\webpack-cli\lib\bootstrap.js:59:9)

Disabling html-webpack-plugin didn't seem to help, and disabling svg-sprite-loader got rid of the error, so I agree with @Thebarda this particular bug is probably originating from somewhere else 🙂

I've filed a bug at https://github.com/JetBrains/svg-sprite-loader/issues/425

Thanks to the help from @sokra I managed to finish up the last two tasks 🎉

I released [email protected] - please let me know if it works for you so we can release a stable version soon

alpha.16 appears to work fine in 3 projects I've tried.

EDIT: make that 4 projects.

alpha-16 works well across 9 projects using it on our side.

Hi there, [email protected] was working fine, but I just upgraded to [email protected] and getting errors on my build; here are some details:

Webpack execution error log

{
  version: '5.10.3',
  time: 14029,
  assetsByChunkName: { index: [ '2bf44e36f5737e2fdea7.bundle.js' ] }
,
  assets: undefined,
  filteredAssets: 27,
  modules: undefined,
  filteredModules: 1430,
  errors: [
    {
      message: '  Error: Child compilation failed:\n' +
        "  Cannot read property 'slice' of undefined\n" +
        "  TypeError: Cannot read property 'slice' of undefined\n" +
        '  \n' +
        '  - plugin-webpack5.js:123 Object.resourceQuery [as fn]\n'
+
        '    [platform]/[vue-loader]/lib/plugin-webpack5.js:123:39\n
' +
        '  \n' +
        '  - RuleSetCompiler.js:99 execRule\n' +
        '    [platform]/[webpack]/lib/rules/RuleSetCompiler.js:99:21
\n' +
        '  \n' +
        '  - RuleSetCompiler.js:118 execRule\n' +
        '    [platform]/[webpack]/lib/rules/RuleSetCompiler.js:118:6
\n' +
        '  \n' +
        '  - RuleSetCompiler.js:137 Object.exec\n' +
        '    [platform]/[webpack]/lib/rules/RuleSetCompiler.js:137:6
\n' +
        '  \n' +
        '  - NormalModuleFactory.js:403 \n' +
        '    [platform]/[webpack]/lib/NormalModuleFactory.js:403:34\
n' +
        '  \n' +
        '  - NormalModuleFactory.js:116 \n' +
        '    [platform]/[webpack]/lib/NormalModuleFactory.js:116:11\
n' +
        '  \n' +
        '  - NormalModuleFactory.js:544 \n' +
        '    [platform]/[webpack]/lib/NormalModuleFactory.js:544:8\n
' +
        '  \n' +
        '  \n' +
        '  - Hook.js:18 Hook.CALL_ASYNC_DELEGATE [as _callAsync]\n'
+
        '    [platform]/[webpack]/[tapable]/lib/Hook.js:18:14\n' +
        '  \n' +
        '  - NormalModuleFactory.js:542 \n' +
        '    [platform]/[webpack]/lib/NormalModuleFactory.js:542:8\n
' +
        '  \n' +
        '  - child-compiler.js:159 \n' +
        '    [platform]/[html-webpack-plugin]/lib/child-compiler.js:
159:18\n' +
        '  \n' +
        '  - Compiler.js:511 \n' +
        '    [platform]/[webpack]/lib/Compiler.js:511:11\n' +
        '  \n' +
        '  - Compiler.js:1059 \n' +
        '    [platform]/[webpack]/lib/Compiler.js:1059:17\n' +
        '  \n' +
        '  \n' +
        '  - Hook.js:18 Hook.CALL_ASYNC_DELEGATE [as _callAsync]\n'
+
        '    [platform]/[webpack]/[tapable]/lib/Hook.js:18:14\n' +
        '  \n' +
        '  - Compiler.js:1055 \n' +
        '    [platform]/[webpack]/lib/Compiler.js:1055:33\n' +
        '  \n' +
        '  - Compilation.js:2119 \n' +
        '    [platform]/[webpack]/lib/Compilation.js:2119:10\n' +
        '  \n' +
        '  \n' +
'  - Hook.js:18 Hook.CALL_ASYNC_DELEGATE [as _callAsync]\n' +

        '    [platform]/[webpack]/[tapable]/lib/Hook.js:18:14\n' +
        '  \n' +
        '  - Compilation.js:2112 \n' +
        '    [platform]/[webpack]/lib/Compilation.js:2112:37\n' +
        '  \n'
    }
  ],
  errorsCount: 2,
  warnings: [],
  warningsCount: 0,
  logging: {
    'webpack.Compiler': { entries: [], filteredEntries: 9, debug: fal
se },
    'webpack.ResolverCachePlugin': { entries: [], filteredEntries: 1,
 debug: false },
    'webpack.FlagDependencyExportsPlugin': { entries: [], filteredEnt
ries: 4, debug: false },
    'webpack.Compilation': { entries: [], filteredEntries: 22, debug:
 false },
    'webpack.SideEffectsFlagPlugin': { entries: [], filteredEntries:
1, debug: false },
    'webpack.buildChunkGraph': { entries: [], filteredEntries: 13, de
bug: false },
    'webpack.SplitChunksPlugin': { entries: [], filteredEntries: 4, d
ebug: false },
    'webpack.FileSystemInfo': { entries: [], filteredEntries: 14, deb
ug: false }
  }
}
[21:18:58] About to exit with code: 0
'    [platform]/[webpack]/[tapable]/lib/Hook.js:18:14\n' +
        '  \n' +
        '  - Compilation.js:2112 \n' +
        '    [platform]/[webpack]/lib/Compilation.js:2112:37\n' +
        '  \n'
    }
  ],
  errorsCount: 2,
  warnings: [],
  warningsCount: 0,
  logging: {
    'webpack.Compiler': { entries: [], filteredEntries: 9, debug: false },
'webpack.ResolverCachePlugin': { entries: [], filteredEntries: 1, debug: false },
    'webpack.FlagDependencyExportsPlug    'webpack.FlagDependencyExportsPlugin': { entries: [], filteredEntries: 4, debug: false },
    'webpack.Compilation': { entries: [], filteredEntries: 22, debug: false },
    'webpack.SideEffectsFlagPlugin': { entries: [], filteredEntries: 1, debug: false },
    'webpack.buildChunkGraph': { entries: [], filteredEntries: 13, debug: false },
    'webpack.SplitChunksPlugin': { entries: [], filteredEntries: 4, debug: false },
    'webpack.FileSystemInfo': { entries: [], filteredEntries: 14, debug: false }
  }
}

webpack.js Plugins declaration

"plugins": [
    new CleanWebpackPlugin(),
    new webpack.EnvironmentPlugin({
        "NODE_ENV": env.NODE_ENV,
        "DEFAULT_LOCALE": "en-US",
        "DEFAULT_FALLBACK": "en-US"
    }),
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin({
        "filename": path.join(__dirname, "index.html"),
        "template": path.join(__dirname, "index.ejs")
    }),
    new ScriptExtHtmlWebpackPlugin({
        "defaultAttribute": "async"
    })
],

Dependencies

OS: Win 10 pro

Captura de tela 2020-12-15 212053

Extra info

  1. It was working as-is with v-16.
  2. I have other modules with different codes, and they all behave the same.

Let me know if I can provide anything else

same to @jungleBadger, my operation is "mac os 11"

@AviVahl @csvan sorry I meant [email protected]

@jungleBadger @qizf7 - thanks I could reproduce the behaviour here:
https://codesandbox.io/s/html-webpack-plugin-5x-alpha-vue-6n1ub?file=/webpack.config.js:0-360

const HtmlWebpackPlugin = require("html-webpack-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");

module.exports = {
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: "vue-loader"
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
    new HtmlWebpackPlugin({
      template: "./src/template.ejs"
    })
  ]
};

According to the stack the error happens in vue-loader: [platform]/[vue-loader]/lib/plugin-webpack5.js:123:39 here:
https://github.com/vuejs/vue-loader/blob/74020775b3e5a814c87d99381564e0d9e3d8d912/lib/plugin-webpack5.js#L123

I opened an issue at the vue-loader repo:

https://github.com/vuejs/vue-loader/issues/1771

It looks like that [email protected] is using a new webpack 5 feature which is not supported by vue-loader: https://github.com/vuejs/vue-loader/issues/1771#issuecomment-745901553

Hopefully this will not cause additional issues with similar loaders or plugins..

I created https://github.com/webpack/webpack/issues/12214 so maybe it can be solved directly by webpack

The vue loader issue is fixed with vue-loader >= 16.1.2

alpha 17 causes:

Cannot read property 'startsWith' of undefined
Error: Child compilation failed:
  TypeError: Cannot read property 'startsWith' of undefined

  - RuleSetCompiler.js:220 Object.fn
    [RVSNew]/[webpack]/lib/rules/RuleSetCompiler.js:220:20

  - RuleSetCompiler.js:99 execRule
    [RVSNew]/[webpack]/lib/rules/RuleSetCompiler.js:99:21

  - RuleSetCompiler.js:118 execRule
    [RVSNew]/[webpack]/lib/rules/RuleSetCompiler.js:118:6

  - RuleSetCompiler.js:137 Object.exec
    [RVSNew]/[webpack]/lib/rules/RuleSetCompiler.js:137:6

  - NormalModuleFactory.js:403 
    [RVSNew]/[webpack]/lib/NormalModuleFactory.js:403:34

  - NormalModuleFactory.js:116 
    [RVSNew]/[webpack]/lib/NormalModuleFactory.js:116:11

  - NormalModuleFactory.js:544 
    [RVSNew]/[webpack]/lib/NormalModuleFactory.js:544:8

  - Hook.js:18 Hook.CALL_ASYNC_DELEGATE [as _callAsync]
    [RVSNew]/[webpack]/[tapable]/lib/Hook.js:18:14

  - NormalModuleFactory.js:542 
    [RVSNew]/[webpack]/lib/NormalModuleFactory.js:542:8

  - child-compiler.js:159 
    [RVSNew]/[html-webpack-plugin]/lib/child-compiler.js:159:18

  - Compiler.js:511 
    [RVSNew]/[webpack]/lib/Compiler.js:511:11

  - Compiler.js:1059 
    [RVSNew]/[webpack]/lib/Compiler.js:1059:17

  - task_queues:93 processTicksAndRejections
    node:internal/process/task_queues:93:5

Previously it worked as expected with alpha 14. It also works normally with alpha 16. I suspect export-loader or webpack externals have conflicts with alpha 17.

@geart891 the latest alpha 17 is using a new webpack 5 feature which seems to be unsupported by one of you other plugins or loaders - see https://github.com/webpack/webpack/issues/12214

I get this error and it's gone when I commented html-loader.

@olegshtch can you please try to build up a minimal webpack config (only html-webpack-plugin and html-loader) which causes this problem? (similar to this one for vue-loader https://github.com/jantimon/html-webpack-plugin/issues/1527#issuecomment-745838536)

Looks like there still conflict between vue-loader and html-loader. If I disable vue-loader instead of html-loader error is also gone.

Yeah, I believe that webpack should at least provide some ways for lib author/end users to migrate to the new changes. This would break almost all current loaders/plugins.

Previously it worked as expected with alpha 14. It also works normally with alpha 16. I suspect export-loader or webpack externals have conflicts with alpha 17.

I have the same with 17 but reverting to 16 works for me. The conflict is with externals for me.

@jantimon Any specific reason to use compiler.hooks.initialize? I have a project applying html-webpack-plugin dynamically, i.e., it's applied later, and it seems the new html-webpack-plugin won't work in my case when I run invalidate() from webpack-dev-middleware, code sample like below:

const compiler = webpack(webpackConfig) // html-webpack-plugin not applied yet
// some time later
new HtmlWebpackPlugin({// ...}).apply(compiler);
devMiddlewareInstance.invalidate()

You can see the real code here https://github.com/chenxsan/voidjs/pull/337/files#diff-7d669522a9bb8bb9e6c420b960b60a516b91678c76c748758c81d43bd8abc131R111-R117

Maybe it's because the initialize hook was already called when I was applying html-webpack-plugin? And invalidate() won't evoke it again.

BTW, it works fine in the html-webpack-plugin v4 version.

I need access to information which are not available in the apply phase anymore (with webpack 5).
Therefore I have to use initialize - I understand the problem you are describing but I don't know how it can be solved.. you would have to ask @sokra or someone else from the webpack core team

@jantimon not seeing any issues with beta-17 on the same 9 projects.

beta-17 also works for me, in one project I tried so far, but is fairly basic.

I need access to information which are not available in the apply phase anymore (with webpack 5).
Therefore I have to use initialize - I understand the problem you are describing but I don't know how it can be solved.. you would have to ask @sokra or someone else from the webpack core team

Can you share which information so I can check?

alpha 17 causes:

Cannot read property 'startsWith' of undefined
Error: Child compilation failed:
  TypeError: Cannot read property 'startsWith' of undefined

  - RuleSetCompiler.js:220 Object.fn
    [RVSNew]/[webpack]/lib/rules/RuleSetCompiler.js:220:20

  - RuleSetCompiler.js:99 execRule
    [RVSNew]/[webpack]/lib/rules/RuleSetCompiler.js:99:21

  - RuleSetCompiler.js:118 execRule
    [RVSNew]/[webpack]/lib/rules/RuleSetCompiler.js:118:6

  - RuleSetCompiler.js:137 Object.exec
    [RVSNew]/[webpack]/lib/rules/RuleSetCompiler.js:137:6

  - NormalModuleFactory.js:403 
    [RVSNew]/[webpack]/lib/NormalModuleFactory.js:403:34

  - NormalModuleFactory.js:116 
    [RVSNew]/[webpack]/lib/NormalModuleFactory.js:116:11

  - NormalModuleFactory.js:544 
    [RVSNew]/[webpack]/lib/NormalModuleFactory.js:544:8

  - Hook.js:18 Hook.CALL_ASYNC_DELEGATE [as _callAsync]
    [RVSNew]/[webpack]/[tapable]/lib/Hook.js:18:14

  - NormalModuleFactory.js:542 
    [RVSNew]/[webpack]/lib/NormalModuleFactory.js:542:8

  - child-compiler.js:159 
    [RVSNew]/[html-webpack-plugin]/lib/child-compiler.js:159:18

  - Compiler.js:511 
    [RVSNew]/[webpack]/lib/Compiler.js:511:11

  - Compiler.js:1059 
    [RVSNew]/[webpack]/lib/Compiler.js:1059:17

  - task_queues:93 processTicksAndRejections
    node:internal/process/task_queues:93:5

Previously it worked as expected with alpha 14. It also works normally with alpha 16. I suspect export-loader or webpack externals have conflicts with alpha 17.

this issue has been fixed by [email protected] 🎉🎉🎉
webpack/webpack#12225

Cool in that case I will release alpha 17 as first beta release 🎉:

[email protected]

beta.1 works well in several projects I've tried. All these projects do have a similar set of loaders/plugins though...
I did notice it pins the version of tapable to 2.0.0, giving me duplicate versions in node_modules. Any chance a caret could be used?

For me it seems inject: false isn't properly respected - I still get script tags (in headTags).

PS. Sorry for not having a proper repro (no time), but I thought it be nice for everybody to hear about it anyway.
PS2. Otherwise it seems to work great (for my quite weird case). Possibly also favicons plugin which is really nice since it's still more unproven!

@cjblomqvist as you can see inject: false doesn't inject anything:

https://html-webpack-plugin.js.org/?code=new%20HtmlWebpackPlugin(%7B%0A%20%20%20inject%3A%20false%0A%7D)%0A

So far the feedback of the beta is quite good - there is only one bigger bug which seems to be caused by a webpack bug. (https://github.com/webpack/webpack/issues/12283)
The webpack core team is already working on it so it will probably disappear soon :)

@AviVahl thanks for your feedback 5.0.0-beta.4 is now using ^2.0.0 :)

beta.4 works well from my end. Thanks for the fixes ❤️

Very very cool progress @jantimon! Thank you so much!

Hello @jantimon, I have some issues with html-webpack-harddisk-plugin along side [email protected].
Here is my configuration :

   new HtmlWebpackPlugin({
      alwaysWriteToDisk: true,
      template: './www/front_src/public/index.html',
      filename: 'index.html',
    }),
    new HtmlWebpackHarddiskPlugin({
      outputPath: path.resolve(`${__dirname}/www`),
    }),

In production mode, I generates 2 index.html files. So first one is generated at the right place (following my outputPath) but it contains the wrong link to my CSS files. The other is generated at the same place as my static JS and CSS files and it contains the good links to my CSS files.

I hope I was clear enough :)

@Thebarda thanks for you feedback - can you please create an issue directly for the html-webpack-hardisk-plugin with a little bit more info which css urls you would expect and which you get instead?

FYI, I fixed it by moving the file path into filename

   new HtmlWebpackPlugin({
      alwaysWriteToDisk: true,
      template: './www/front_src/public/index.html',
      filename: path.resolve(`${__dirname}/www/index.html`)',
    }),
    new HtmlWebpackHarddiskPlugin(),

It produces an HTML file at the right place with the right hash inside CSS urls

FYI for anyone interested, webpack/webpack#12283 was resolved in [email protected].

It looks like everything works well so I will release html-webpack-plugin 5.x as a stable release soon

Ok, then just press "merge" button :) we are getting DEP_WEBPACK_COMPILATION_ASSETS with current version. Thank you!

@jantimon sounds good - any issues blocking the v5 release?

looks like webpack 5 support was merged to master yesterday but has not been released, is that intentional?

@jantimon thank you for your amazing work. I guess we are all looking forward for the release. Would love to see this nasty DEP_WEBPACK_COMPILATION_ASSETS warning to go away :)

Is there anything that blocks the release right now? We are using only the small subset of the plugin features, but I've tried the 5.0.0-beta.6 version and it works great for us.

released as html-webpack-plugin 5.0.0

Was this page helpful?
0 / 5 - 0 ratings