Giter Club home page Giter Club logo

html-webpack-plugin's Introduction

npm node npm tests Backers on Open Collective Sponsors on Open Collective

HTML Webpack Plugin

Plugin that simplifies creation of HTML files to serve your bundles

Install

Webpack 5

  npm i --save-dev html-webpack-plugin
  yarn add --dev html-webpack-plugin

Webpack 4

  npm i --save-dev html-webpack-plugin@4
  yarn add --dev html-webpack-plugin@4

This is a webpack plugin that simplifies creation of HTML files to serve your webpack bundles. This is especially useful for webpack bundles that include a hash in the filename which changes every compilation. You can either let the plugin generate an HTML file for you, supply your own template using lodash templates or use your own loader.

Sponsors

Thanks for supporting the ongoing improvements to the html-webpack-plugin!

Zero Config

The html-webpack-plugin works without configuration.
It's a great addition to the ⚙️ webpack-config-plugins.

Plugins

The html-webpack-plugin provides hooks to extend it to your needs. There are already some really powerful plugins which can be integrated with zero configuration

Usage

The plugin will generate an HTML5 file for you that includes all your webpack bundles in the head using script tags. Just add the plugin to your webpack config as follows:

webpack.config.js

const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: "index.js",
  output: {
    path: __dirname + "/dist",
    filename: "index_bundle.js",
  },
  plugins: [new HtmlWebpackPlugin()],
};

This will generate a file dist/index.html containing the following

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Webpack App</title>
    <script defer src="index_bundle.js"></script>
  </head>
  <body></body>
</html>

If you have multiple webpack entry points, they will all be included with script tags in the generated HTML.

If you have any CSS assets in webpack's output (for example, CSS extracted with the mini-css-extract-plugin) then these will be included with <link> tags in the HTML head.

If you have plugins that make use of it, html-webpack-plugin should be ordered first before any of the integrated Plugins.

Options

You can pass a hash of configuration options to html-webpack-plugin. Allowed values are as follows:

Name Type Default Description
title {String} Webpack App The title to use for the generated HTML document
filename {String|Function} 'index.html' The file to write the HTML to. Defaults to index.html. You can specify a subdirectory here too (eg: assets/admin.html). The [name] placeholder will be replaced with the entry name. Can also be a function e.g. (entryName) => entryName + '.html'.
template {String} `` webpack relative or absolute path to the template. By default it will use src/index.ejs if it exists. Please see the docs for details
templateContent {string|Function|false} false Can be used instead of template to provide an inline template - please read the Writing Your Own Templates section
templateParameters {Boolean|Object|Function} false Allows to overwrite the parameters used in the template - see example
inject {Boolean|String} true true || 'head' || 'body' || false Inject all assets into the given template or templateContent. When passing 'body' all javascript resources will be placed at the bottom of the body element. 'head' will place the scripts in the head element. Passing true will add it to the head/body depending on the scriptLoading option. Passing false will disable automatic injections. - see the inject:false example
publicPath {String|'auto'} 'auto' The publicPath used for script and link tags
scriptLoading {'blocking'|'defer'|'module'|'systemjs-module'} 'defer' Modern browsers support non blocking javascript loading ('defer') to improve the page startup performance. Setting to 'module' adds attribute type="module". This also implies "defer", since modules are automatically deferred.
favicon {String} `` Adds the given favicon path to the output HTML
meta {Object} {} Allows to inject meta-tags. E.g. meta: {viewport: 'width=device-width, initial-scale=1, shrink-to-fit=no'}
base {Object|String|false} false Inject a base tag. E.g. base: "https://example.com/path/page.html
minify {Boolean|Object} true if mode is 'production', otherwise false Controls if and in what ways the output should be minified. See minification below for more details.
hash {Boolean} false If true then append a unique webpack compilation hash to all included scripts and CSS files (i.e. main.js?hash=compilation_hash). This is useful for cache busting
cache {Boolean} true Emit the file only if it was changed
showErrors {Boolean} true Errors details will be written into the HTML page
chunks {?} ? Allows you to add only some chunks (e.g only the unit-test chunk)
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}
excludeChunks {Array.<string>} `` Allows you to skip some chunks (e.g don't add the unit-test chunk)
xhtml {Boolean} false If true render the link tags as self-closing (XHTML compliant)

Here's an example webpack config illustrating how to use these options

webpack.config.js

{
  entry: 'index.js',
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js'
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'My App',
      filename: 'assets/admin.html'
    })
  ]
}

Generating Multiple HTML Files

To generate more than one HTML file, declare the plugin more than once in your plugins array

webpack.config.js

{
  entry: 'index.js',
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js'
  },
  plugins: [
    new HtmlWebpackPlugin(), // Generates default index.html
    new HtmlWebpackPlugin({  // Also generate a test.html
      filename: 'test.html',
      template: 'src/assets/test.html'
    })
  ]
}

Writing Your Own Templates

If the default generated HTML doesn't meet your needs you can supply your own template. The easiest way is to use the template option and pass a custom HTML file. The html-webpack-plugin will automatically inject all necessary CSS, JS, manifest and favicon files into the markup.

Details of other template loaders are documented here.

plugins: [
  new HtmlWebpackPlugin({
    title: "Custom template",
    // Load a custom template (lodash by default)
    template: "index.html",
  }),
];

index.html

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body></body>
</html>

If you already have a template loader, you can use it to parse the template. Please note that this will also happen if you specify the html-loader and use .html file as template.

webpack.config.js

module: {
  loaders: [
    { test: /\.hbs$/, loader: "handlebars-loader" }
  ]
},
plugins: [
  new HtmlWebpackPlugin({
    title: 'Custom template using Handlebars',
    template: 'index.hbs'
  })
]

You can use the lodash syntax out of the box. If the inject feature doesn't fit your needs and you want full control over the asset placement use the default template of the html-webpack-template project as a starting point for writing your own.

The following variables are available in the template by default (you can extend them using the templateParameters option):

  • htmlWebpackPlugin: data specific to this plugin

    • htmlWebpackPlugin.options: the options hash that was passed to the plugin. In addition to the options actually used by this plugin, you can use this hash to pass arbitrary data through to your template.

    • htmlWebpackPlugin.tags: the prepared headTags and bodyTags Array to render the <base>, <meta>, <script> and <link> tags. Can be used directly in templates and literals. For example:

      <html>
        <head>
          <%= htmlWebpackPlugin.tags.headTags %>
        </head>
        <body>
          <%= htmlWebpackPlugin.tags.bodyTags %>
        </body>
      </html>
    • htmlWebpackPlugin.files: direct access to the files used during the compilation.

      publicPath: string;
      js: string[];
      css: string[];
      manifest?: string;
      favicon?: string;
  • webpackConfig: the webpack configuration that was used for this compilation. This can be used, for example, to get the publicPath (webpackConfig.output.publicPath).

  • compilation: the webpack compilation object. This can be used, for example, to get the contents of processed assets and inline them directly in the page, through compilation.assets[...].source() (see the inline template example).

The template can also be directly inlined directly into the options object.
⚠️ templateContent does not allow to use webpack loaders for your template and will not watch for template file changes

webpack.config.js

new HtmlWebpackPlugin({
  templateContent: `
    <html>
      <body>
        <h1>Hello World</h1>
      </body>
    </html>
  `,
});

The templateContent can also access all templateParameters values.
⚠️ templateContent does not allow to use webpack loaders for your template and will not watch for template file changes

webpack.config.js

new HtmlWebpackPlugin({
  inject: false,
  templateContent: ({ htmlWebpackPlugin }) => `
    <html>
      <head>
        ${htmlWebpackPlugin.tags.headTags}
      </head>
      <body>
        <h1>Hello World</h1>
        ${htmlWebpackPlugin.tags.bodyTags}
      </body>
    </html>
  `,
});

Filtering Chunks

To include only certain chunks you can limit the chunks being used

webpack.config.js

plugins: [
  new HtmlWebpackPlugin({
    chunks: ["app"],
  }),
];

It is also possible to exclude certain chunks by setting the excludeChunks option

webpack.config.js

plugins: [
  new HtmlWebpackPlugin({
    excludeChunks: ["dev-helper"],
  }),
];

Minification

If the minify option is set to true (the default when webpack's mode is 'production'), the generated HTML will be minified using html-minifier-terser and the following options:

{
  collapseWhitespace: true,
  keepClosingSlash: true,
  removeComments: true,
  removeRedundantAttributes: true,
  removeScriptTypeAttributes: true,
  removeStyleLinkTypeAttributes: true,
  useShortDoctype: true
}

To use custom html-minifier options pass an object to minify instead. This object will not be merged with the defaults above.

To disable minification during production mode set the minify option to false.

Meta Tags

If the meta option is set the html-webpack-plugin will inject meta tags.
For the default template the html-webpack-plugin will already provide a default for the viewport meta tag.

Please take a look at this well maintained list of almost all possible meta tags.

name/content meta tags

Most meta tags are configured by setting a name and a content attribute.
To add those use a key/value pair:

webpack.config.js

plugins: [
  new HtmlWebpackPlugin({
    meta: {
      viewport: "width=device-width, initial-scale=1, shrink-to-fit=no",
      // Will generate: <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      "theme-color": "#4285f4",
      // Will generate: <meta name="theme-color" content="#4285f4">
    },
  }),
];

Simulate http response headers

The http-equiv attribute is essentially used to simulate a HTTP response header.
This format is supported using an object notation which allows you to add any attribute:

webpack.config.js

plugins: [
  new HtmlWebpackPlugin({
    meta: {
      "Content-Security-Policy": {
        "http-equiv": "Content-Security-Policy",
        content: "default-src https:",
      },
      // Will generate: <meta http-equiv="Content-Security-Policy" content="default-src https:">
      // Which equals to the following http header: `Content-Security-Policy: default-src https:`
      "set-cookie": {
        "http-equiv": "set-cookie",
        content: "name=value; expires=date; path=url",
      },
      // Will generate: <meta http-equiv="set-cookie" content="value; expires=date; path=url">
      // Which equals to the following http header: `set-cookie: value; expires=date; path=url`
    },
  }),
];

Base Tag

When the base option is used, html-webpack-plugin will inject a base tag. By default, a base tag will not be injected.

The following two are identical and will both insert <base href="http://example.com/some/page.html">:

new HtmlWebpackPlugin({
  base: "http://example.com/some/page.html",
});
new HtmlWebpackPlugin({
  base: { href: "http://example.com/some/page.html" },
});

The target can be specified with the corresponding key:

new HtmlWebpackPlugin({
  base: {
    href: "http://example.com/some/page.html",
    target: "_blank",
  },
});

which will inject the element <base href="http://example.com/some/page.html" target="_blank">.

Long Term Caching

For long term caching add contenthash to the filename.

Example:

plugins: [
  new HtmlWebpackPlugin({
    filename: "index.[contenthash].html",
  }),
];

contenthash is the hash of the content of the output file.

Refer webpack's Template Strings for more details

Events

To allow other plugins to alter the HTML this plugin executes tapable hooks.

The lib/hooks.js contains all information about which values are passed.

Concept flow uml

beforeAssetTagGeneration hook

    AsyncSeriesWaterfallHook<{
      assets: {
        publicPath: string,
        js: Array<{string}>,
        css: Array<{string}>,
        favicon?: string | undefined,
        manifest?: string | undefined
      },
      outputName: string,
      plugin: HtmlWebpackPlugin
    }>

alterAssetTags hook

    AsyncSeriesWaterfallHook<{
      assetTags: {
        scripts: Array<HtmlTagObject>,
        styles: Array<HtmlTagObject>,
        meta: Array<HtmlTagObject>,
      },
      publicPath: string,
      outputName: string,
      plugin: HtmlWebpackPlugin
    }>

alterAssetTagGroups hook

    AsyncSeriesWaterfallHook<{
      headTags: Array<HtmlTagObject | HtmlTagObject>,
      bodyTags: Array<HtmlTagObject | HtmlTagObject>,
      publicPath: string,
      outputName: string,
      plugin: HtmlWebpackPlugin
    }>

afterTemplateExecution hook

    AsyncSeriesWaterfallHook<{
      html: string,
      headTags: Array<HtmlTagObject | HtmlTagObject>,
      bodyTags: Array<HtmlTagObject | HtmlTagObject>,
      outputName: string,
      plugin: HtmlWebpackPlugin,
    }>

beforeEmit hook

    AsyncSeriesWaterfallHook<{
      html: string,
      outputName: string,
      plugin: HtmlWebpackPlugin,
    }>

afterEmit hook

    AsyncSeriesWaterfallHook<{
      outputName: string,
      plugin: HtmlWebpackPlugin
    }>

Example implementation: webpack-subresource-integrity

plugin.js

// If your plugin is direct dependent to the html webpack plugin:
const HtmlWebpackPlugin = require("html-webpack-plugin");
// If your plugin is using html-webpack-plugin as an optional dependency
// you can use https://github.com/tallesl/node-safe-require instead:
const HtmlWebpackPlugin = require("safe-require")("html-webpack-plugin");

class MyPlugin {
  apply(compiler) {
    compiler.hooks.compilation.tap("MyPlugin", (compilation) => {
      console.log("The compiler is starting a new compilation...");

      // Static Plugin interface |compilation |HOOK NAME | register listener
      HtmlWebpackPlugin.getCompilationHooks(compilation).beforeEmit.tapAsync(
        "MyPlugin", // <-- Set a meaningful name here for stacktraces
        (data, cb) => {
          // Manipulate the content
          data.html += "The Magic Footer";
          // Tell webpack to move on
          cb(null, data);
        },
      );
    });
  }
}

module.exports = MyPlugin;

webpack.config.js

plugins: [new MyPlugin({ options: "" })];

Note that the callback must be passed the HtmlWebpackPluginData in order to pass this onto any other plugins listening on the same beforeEmit event

Maintainers


Jan Nicklas

Thomas Sileghem

Backers

Thank you to all our backers!
If you want to support the project as well become a sponsor or a a backer.

Contributors

This project exists thanks to all the people who contribute.

You're free to contribute to this project by submitting issues and/or pull requests. This project is test-driven, so keep in mind that every change and new feature should be covered by tests.

html-webpack-plugin's People

Contributors

alexander-akait avatar ampedandwired avatar anjianshi avatar ascariandrea avatar austaras avatar avivahl avatar cgreening avatar chenxsan avatar edmorley avatar foglerek avatar gabrielcsapo avatar graingert avatar jantimon avatar kennyt avatar mastilver avatar michael-ciniawsky avatar mistadikay avatar numical avatar okhomenko avatar rodneyrehm avatar sandeep45 avatar sibiraj-s avatar simenb avatar sokra avatar spacek33z avatar spuf avatar swimmadude66 avatar tschmidtb51 avatar vincent-ng avatar zzuieliyaoli avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

html-webpack-plugin's Issues

1.4 template changes broke semver

Just a quick, friendly fyi. I helped @ericwooley to debug html-webpack-plugin to work with https://github.com/mvilrokx/react-starter-template . The problem was that it depended on html-webpack-plugin using ^1.1.0 (major versions). As per semver that will match to major versions (ie. 0.1, 0.2, ... 1.0, 2.0, ...). You can try http://semver.npmjs.com/ to see how it behaves.

The problem is that somewhere between 1.1 and the current version (likely 1.4) backwards compatibility was broken. Due to the way matching works that caused breakage here.

So in short bump major version for backwards incompatible changes. That will keep dependants happy. 👍

I'm not sure what would be a good fix but maybe there's something that could be done. Hope this helps.

Changelog or github releases?

It would be very welcome if the changelog would be kept up to date, or to use the github release otherwise. Trying to find out what changed in between versions is a bit harder then needs to be now.

container div without using a template

I just started using html-webpack-plugin, and it's definitely handy. It fulfills my project needs pretty much out of the box. I just need a simple HTML file to bootstrap my React app, and html-webpack-plugin makes this easy.

I think the plugin could even further simplify my project if it would allow me to specify that I'd like a div container in the default index.html that it creates. React doesn't like being mounted directly to body. Currently, I still have to include an index.html file in my project just to create this div.

Do you think it'd be worth while to add a config setting that automatically includes an optional container div, if desired? Maybe a setting like includeContainer, where the default would be false or undefined, or something falsy. If it were true, it could just include a div with an id of "container" or something. If it were a string, it could include a div where the string is the id value.

includeContainer: true
includeContainer: false
includeContainer: "fooContainer"

files.main is not working like assets.main

Deprecated still works with the famous Error undefined ..
<script type="application/javascript" src="{%=o.htmlWebpackPlugin.assets.main%}"></script>

However the real problem is :
<script type="application/javascript" src="{%=o.htmlWebpackPlugin.files.main%}"></script>
Now results in
<script type="application/javascript" src=""></script> on the build. What am I missing and if I am is there better docs for the transition? The only thing that works for me is
<script type="application/javascript" src="{%=o.htmlWebpackPlugin.files.js%}"></script>

Multiple bundles

I have a use case where I'm using the ExtractTextPlugin for generating a css file. In this case there's an extra bundle generated for the same chunk (one js file and one css file).
Looking at the code I see that you're just taking the first element when the chunk is an array, but with my use case I would need to get access to the second item which is the css file.
The ideal option here would be to get the specific item from the array by specifying the index in the template, like this: {%=o.htmlWebpackPlugin.assets.styles[1]%} and fallback to the first item when not specifying an index.
With the current codebase this doesn't seem doable, as you just pass the data structure to the template engine.
Any thoughts? For my own use I just changed it so you always need to specify the index when the chunk is an array, but this won't work when switching back and forth between building with and without source maps.

using image assets

How can I include assets that aren't JS or CSS?

It obviously requires a custom template, but somehow I need to specify that I will need these files so they get added to the list of assets. I think it needs to work the same way favicon does.

        <link rel="apple-touch-icon" href="assets/img/touch-icon-iphone.png">
        <link rel="apple-touch-icon" sizes="76x76" href="assets/img/touch-icon-ipad.png">
        <link rel="apple-touch-icon" sizes="120x120" href="assets/img/touch-icon-iphone-retina.png">
        <link rel="apple-touch-icon" sizes="152x152" href="assets/img/touch-icon-ipad-retina.png">

question: do i need <script src="http://localhost:8080/webpack-dev-server.js"></script> in my template for refresh/reload?

i've found that my template needs to look like (with the script tag):

<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <div id='myId'></div>
    <script src="http://localhost:8080/webpack-dev-server.js"></script>
  </body>
</html>

to get either refresh or hot reload working with config similar to:

var HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: {
    app: [
      'webpack/hot/dev-server',
      './app/app.js'
    ]
  },
  output: {
    path: './build',
    filename: "bundle.js"
  },
  resolve: {
    extensions: ['', '.js'],
  },
  module: {
    loaders: [
      { test: /\.scss$/, loader: 'style!css!sass' },
      { test: /\.js$/, loader: 'babel', query: {stage: 1} }
    ]
  },
  devtool: 'cheap-module-eval-source-map',
  debug: true,
  plugins: [
    new HtmlWebpackPlugin({template: 'index.html', inject: 'body'})
  ]
};

is that expected, or is there any way to get the plugin to manage that script tag...?

on a related note, would it be accurate to say that, generally, the plugin only works against http://localhost:8080/ and doesn't work against http://localhost:8080/webpack-dev-server/bundle as the latter hijacks index.html?

How to add styles

  module: {
    loaders: [
        {
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract("style", "css!sass")
        },


plugins: [
    new ExtractTextPlugin("style.[hash].css", {
        allChunks: true
    }),
    new HtmlWebpackPlugin({
        template: 'src/client/index.html',
        "assets": {
            "client" : "client.[hash].js",
            "style"  : "style.[hash].css",
        }
    })
]

template:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
    <title>My App</title>
  </head>
  <body>
    <link href="{%=o.htmlWebpackPlugin.assets.style%}" media="all" rel="stylesheet" type="text/css">
    <script src="{%=o.htmlWebpackPlugin.assets.client%}"></script>
  </body>
</html>

what am i doing wrong?: Cannot resolve module 'index.js'

hi,

i'm kind of a webpack noob, so prolly doing something stupid, but when i run webpack with the following configuration:

var HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: 'index.js',
  output: {
    path: 'dist',
    filename: 'index_bundle.js'
  },
  module: {
    loaders: [
      { test: /\.scss$/, loader: 'style!css!sass' },
      { test: /\.js$/, loader: 'babel', query: {stage: 1} }
    ]
  },
  devtool: 'cheap-module-eval-source-map',
  debug: true,
  plugins: [new HtmlWebpackPlugin()]
}

i get:

~/g/webpack-scratch (tk/html-plugin) $ webpack
Hash: 96ac1f7bada92e7c9381
Version: webpack 1.9.10
Time: 24ms
     Asset       Size  Chunks             Chunk Names
index.html  142 bytes          [emitted]  

ERROR in Entry module not found: Error: Cannot resolve module 'index.js' in /Users/tony/git/webpack-scratch

here is a link to the entire project for reference...

any guidance appreciated!

best,
tony.

Favicon

Any suggestions on adding a favicon?

Automatically add JS/CSS to HTML files for CDN resources

Tobias seems to think this feature request might be a good fit for your library: webpack/webpack#754 (comment)

I have the following concerns:

  1. I want to provide an existing HTML file.
  2. Ideally, I want to work with well-formed HTML files (not containing any templates). I expect the plugin to append <script> and <link> tags to the end of <head>.

What do you think? Are you willing to add this to this plugin?

Meta images

In my .html file, I have a meta tag like this:

<meta property="og:image" content="/img/screenshot.png">

When I build the file, that image does not get moved over to the build folder. I've also tried this, and it didn't work:

<meta property="og:image" content="<%= require('./assets/img/touch-icon-iphone.png') %>">

Any ideas how to achieve that the image gets moved to the build folder?

Use with chunk-manifest-webpack-plugin

Has anyone been able to get https://github.com/diurnalist/chunk-manifest-webpack-plugin working with html-webpack?

I'm trying to get longterm caching working with chunkNames, but my webpack bootstrap and chunk mapping is getting stored in my common chunk file (which doesn't work with hashed filenames).

I'd love to have this plugin inject the window.webpackManifest variable into my index.html template, but I'm not quite sure how to go about it. Any pointers? Thanks!

gzip/compression support

It doesn't appear like the generated source gets piped through the rest of the webpack plugins (compression, for example). It'd be neat to support that

Unhandled rejection Error: Invalid arguments: 'delay'

This error is pretty new and happens with either v1.4.x or 1.5.x. It seems to be related to bluebird (they released a new version 15 days ago), maybe you should fix the bluebird version.

Till then the Webpack watch is broken.

Unhandled rejection Error: Invalid arguments: 'delay'
    at NodeWatchFileSystem.watch (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/lib/node/NodeWatchFileSystem.js:29:9)
    at Watching.watch (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/lib/Compiler.js:86:47)
    at Watching._done (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/lib/Compiler.js:82:8)
    at Watching.<anonymous> (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/lib/Compiler.js:60:18)
    at Tapable.emitRecords (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/lib/Compiler.js:279:37)
    at Watching.<anonymous> (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/lib/Compiler.js:57:19)
    at /Users/shprink/Sites/bixev/react2pics/node_modules/webpack/lib/Compiler.js:272:11
    at Tapable.applyPluginsAsync (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/node_modules/tapable/lib/Tapable.js:60:69)
    at Tapable.afterEmit (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/lib/Compiler.js:269:8)
    at Tapable.<anonymous> (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/lib/Compiler.js:264:14)
    at done (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/node_modules/async/lib/async.js:132:19)
    at /Users/shprink/Sites/bixev/react2pics/node_modules/webpack/node_modules/async/lib/async.js:32:16
    at MemoryFileSystem.writeFile (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack-dev-server/node_modules/webpack-dev-middleware/node_modules/memory-fs/lib/MemoryFileSystem.js:224:9)
    at Tapable.writeOut (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/lib/Compiler.js:258:27)
    at Tapable.<anonymous> (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/lib/Compiler.js:244:20)
    at /Users/shprink/Sites/bixev/react2pics/node_modules/webpack/node_modules/async/lib/async.js:122:13
    at _each (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/node_modules/async/lib/async.js:46:13)
    at Object.async.each (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/node_modules/async/lib/async.js:121:9)
    at Tapable.emitFiles (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/lib/Compiler.js:233:20)
    at MemoryFileSystem.(anonymous function) [as mkdirp] (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack-dev-server/node_modules/webpack-dev-middleware/node_modules/memory-fs/lib/MemoryFileSystem.js:197:10)
    at Tapable.<anonymous> (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/lib/Compiler.js:227:25)
    at Tapable.next (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/node_modules/tapable/lib/Tapable.js:67:11)
    at Tapable.<anonymous> (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/lib/ProgressPlugin.js:73:4)
    at Tapable.next (/Users/shprink/Sites/bixev/react2pics/node_modules/webpack/node_modules/tapable/lib/Tapable.js:69:14)
    at Object.finallyHandler (/Users/shprink/Sites/bixev/react2pics/node_modules/html-webpack-plugin/node_modules/bluebird/js/main/finally.js:40:23)
    at Object.tryCatcher (/Users/shprink/Sites/bixev/react2pics/node_modules/html-webpack-plugin/node_modules/bluebird/js/main/util.js:24:31)
    at Promise._settlePromiseFromHandler (/Users/shprink/Sites/bixev/react2pics/node_modules/html-webpack-plugin/node_modules/bluebird/js/main/promise.js:454:31)
    at Promise._settlePromiseAt (/Users/shprink/Sites/bixev/react2pics/node_modules/html-webpack-plugin/node_modules/bluebird/js/main/promise.js:530:18)
    at Promise._settlePromises (/Users/shprink/Sites/bixev/react2pics/node_modules/html-webpack-plugin/node_modules/bluebird/js/main/promise.js:646:14)
    at Async._drainQueue (/Users/shprink/Sites/bixev/react2pics/node_modules/html-webpack-plugin/node_modules/bluebird/js/main/async.js:182:16)
    at Async._drainQueues (/Users/shprink/Sites/bixev/react2pics/node_modules/html-webpack-plugin/node_modules/bluebird/js/main/async.js:192:10)
    at Async.drainQueues (/Users/shprink/Sites/bixev/react2pics/node_modules/html-webpack-plugin/node_modules/bluebird/js/main/async.js:15:14)
    at process._tickCallback (node.js:419:13)

How to pass template parameters

side story: Just starting to integrating webpack to replace requirejs.

How to pass template parameters to custom template?

Specify absolute URL of emitted resources?

I want to serve my index.html at a variety of routes: /, /a, /a/b. (This is a Backbone app that does internal routing on a single page.)

Currently, the generated html links to relative resources, assuming that it will only be served from the directory where it's generated. When you instead serve it from /a/b, it looks for resources like bundle.js in /a/bundle.js, which doesn't exist.

Would you consider adding a config option to link to "absolute" URLs (relative to the output path, e.g. /bundle.js) instead of relative ones?

Passing in loader data?

So, I'm fairly new to Webpack, so hopefully this is a good place to ask this.

This request is sort of related to #10, but instead of passing in loader data directly I was hoping to pass it in as a property that can be accessed from the template. I was hoping to pass in my localized styles from css-loader. Something like this:

webpack.config:

new HtmlWebpackPlugin({
    styles: require('style-loader!css-loader?localIdentName=[local]__[hash:base64:5]!autoprefixer-loader?{browsers:["last 2 version", "ie 9"]}!sass-loader!src/scss/main/s.scss'),
    filename: 'main.handlebars',
    template: 'src/tmpl/main.html'
})

main.html:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
        <title>Title</title>
    </head>
    <body class="{%= o.htmlWebpackPlugin.options.styles.bodyClass %}">
    </body>
</html>

Unfortunately, I can't seem to find a configuration that allows me to process a loader in the config. Is this possible?

Thanks!

Expose the `publicPath` option

First of all, thanks for this plugin! This rocks, and therefore you rock!

While looking at the issues, I saw #6 which was exactly my problem, but on example you gave, you added the publicPath manually to the HTML.

This is fine for most projects, however is quite troublesome if your website is going to be deployed on multiple domains and the publicPath changes with each configuration.

Is it possible to expose the publicPath to the templating somehow?

Thanks

Is it possible to inject custom html into body?

Currently I'm injecting some Markdown to my page through React. It gets converted to HTML first by a loader, after that React takes care of it. This doesn't seem particularly nice way to deal with it, though.

Is it possible to inject the custom HTML generated by my Markdown loader within body somehow?

Using template: "TypeError: First argument needs to be a number, array or string."

Hi,

Just started working with webpack and still trying to wrap my head around a lot of things. However, this plugin seems pretty straight forward. But I am trying to convert a gulp-heavy project to a more native react/webpack version but taking stuff small pieces at a time. That includes trying to get a predefined template to be used by this plugin, but when I use the 'template' options, it fails:

$ webpack --progress --colors --watch -d
 95% emit
buffer.js:188
        throw new TypeError('First argument needs to be a number, ' +
              ^
TypeError: First argument needs to be a number, array or string.
    at new Buffer (buffer.js:188:15)
    at Tapable.writeOut (/Users/wrapp/go/src/wrappmin/node_modules/webpack/lib/Compiler.js:247:16)
    at Tapable.<anonymous> (/Users/wrapp/go/src/wrappmin/node_modules/webpack/lib/Compiler.js:236:20)
    at /Users/wrapp/go/src/wrappmin/node_modules/webpack/node_modules/async/lib/async.js:125:13
    at Array.forEach (native)
    at _each (/Users/wrapp/go/src/wrappmin/node_modules/webpack/node_modules/async/lib/async.js:46:24)
    at Object.async.each (/Users/wrapp/go/src/wrappmin/node_modules/webpack/node_modules/async/lib/async.js:124:9)
    at Tapable.emitFiles (/Users/wrapp/go/src/wrappmin/node_modules/webpack/lib/Compiler.js:225:20)
    at /Users/wrapp/go/src/wrappmin/node_modules/webpack/node_modules/mkdirp/index.js:29:20
    at Object.oncomplete (fs.js:108:15)

webpack.config.js:

webpack = require('webpack');
var HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: './src/app.jsx',
    output: {
        path: './build',
        public: '/',
        filename: 'bundle.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'
        })
        //new webpack.optimize.DedupePlugin(),
        //new webpack.optimize.OccurenceOrderPlugin(),
        //new webpack.optimize.UglifyJsPlugin()
    ],
    module: {
        loaders: [
            {
                //tell webpack to use jsx-loader for all *.jsx files
                test: /\.jsx?$/,
                loader: 'jsx-loader?insertPragma=React.DOM&harmony'
            },
            {
                test: /\.css$/,
                loader: 'style!css'
            },
            {
                test: /\.json$/,
                loader:'json-loader'
            }
        ]
    },
    resolve: {
        extensions: ['', '.js', '.jsx', '.json', '.css']
    }
};

template:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"/>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"/>
        <link rel="stylesheet" href="https://d3ddaigw5mx5fo.cloudfront.net/next/res11/css/fonts.css"/>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.css" />
        <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.js"></script>
        <script src="{%=o.htmlWebpackPlugin.files.chunks.head.entry%}"></script>
    </head>
    <body>
        <script src="{%=o.htmlWebpackPlugin.files.chunks.main.entry%}"></script>
    </body>
</html>

As you might understand I want to replace the CDN stuff as well but that I will do when I get the current issue solved.

Would love to get some help with this.

Cheers
--Marcus

Template change doesn't trigger recompilation in watch mode

Hi. Thanks for the great plugin.
There is one minor issue though I'm not sure is it the right place to address it.

When I run webpack-dev-server and change some javascript file in dependency graph, webpack notices it and recompiles the bundle. But it doesn't work for html-webpack-plugin templates. Could this be fixed? Thanks.

Separate css and js directories lead to incorrect paths in html

{
  output: {
    path: path.resolve('build/js'),
    publicPath: '',
    filename: '[name].js'
  },

  plugins: [
    new ExtractTextPlugin('../css/[name].css'),

    new HtmlPlugin({
      template: 'example.html',
      filename: '../index.html'
    })
  ],

  ...
}

The structure ends up looking like:

build/
    index.html
    js/
        main.js
    css/
        main.css

Using o.htmlWebpackPlugin.files in the template, the link and script tags end up looking like:

<link href="../css/main.css" rel="stylesheet">
<script src="main.js"></script>

Expected:

<link href="css/main.css" rel="stylesheet">
<script src="js/main.js"></script>

Allow using a loader

I'm not sure if this is a useful idea for other people, but it happens that my index.html file already contains some images. It would be nice to add the images to webpack's dependency graph.

Is it possible to use the html-loader in conjunction with this plugin? Or is this idea too farfetched?

Once again, thanks.

Support for chunk hashes

I'd like to use chunk hashes since I'm dealing with a large amount of files used in all sorts of ways, and busting cache on each deployment for all files isn't ideal.

Seems like it'd be possible to add the chunkhash to each chunk object, so this is possible:

{%=o.htmlWebpackPlugin.files.chunks.main.entry%}?{%=o.htmlWebpackPlugin.files.chunks.main.chunkhash%}

And this could be automated so you can pass chunkhash: true and add that as a query param.

If this sounds good, I'd be glad to make a PR!

How to use plugin with webpack-dev-server?

Hi! I have problem when using plugin with webpack-dev-server.

I've rendered my index.html but it stays in memory, not in the content-base folder where static should be located. So browser cannot find any index.html and gives 404 error.

blueimp template typo on npm page

Not sure if this is where I should report this, but, there's a missing % sign in an example on the npm page. I copied/pasted the example but I kept getting an error like this "ERROR in HtmlWebpackPlugin: template error Syntax Error: Unexpected token =", but finally realized it was because of the missing % sign.

screen shot 2015-07-07 at 2 49 38 pm

By the way, this plugin is a huge help!

Changing template doesn't trigger build when watching

Related to #5. I'm not sure if this is a regression, due to a change in webpack, or me just not knowing what I'm doing. I'm not able to get my template to rebuild or reload with either webpack -w or webpack-dev-server. I have to run webpack manually every time.

Config:

var HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: "./app/index.js",
    devtool: "source-map",
    output: {
        path: "./build",
        filename: "bundle.js",
        sourceMapFilename: "[file].map"
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: "index.html",
            template: "./app/index.html"
        })
    ],
    module: {
        loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: "babel-loader"
            }
        ]
    }
};

app/index.html:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="{%=o.htmlWebpackPlugin.files.chunks.main.entry%}"></script>
</head>
<body>
</body>
</html>

Regression when using minify in v1.6.2

#81 is a breaking change, it shouldn't be released in v1.6.2. I was passing in true or false depending on my environment, (admittedly I hadn't looked at my output, I just assumed it was being minified) and the v1.6.2 release broke my builds.

Adding a check such as: minify = minify === true ? {} : minify could be released as v1.6.3 and it would preserve backwards compatibility.

How to Automatically Include Styles?

hi there, apologies if this is a bit of a noob question, but how does one automatically have styles included in the built html file? i can't seem to get them included with the following config:

module.exports = {
  entry: [
    'webpack/hot/dev-server',
    './src/app/main.js',
  ],

  output: {
    path: './dist/',
    filename: 'app.js',
    hash: true
  },

  module: {
    loaders: [
      { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
      { test: /\.js$/, loader: 'jsx-loader' }, // required for react jsx
      { test: /\.jsx$/, loader: 'jsx-loader?insertPragma=React.DOM' },
      { test: /\.(woff|ttf|eot|svg)$/, loader: 'file-loader' },
      { test: /\.css$/, loader: 'style!css!autoprefixer' },
      { test: /\.sass$/, loader: 'style!css!autoprefixer!sass?indentedSyntax' }
    ]
  },

  resolve: {
    root: [
      path.resolve(__dirname, './src'),
      path.resolve(__dirname, './node_modules')
    ]
  },

  plugins: [
    new HtmlWebpackPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
  ],
};

and this is the structure of my src/app/ directory which contains my entry and my stylesheets:

src/app/
├── index.html
├── main.js
├── static
└── styles
    └── app.sass

do i need to reference that stylesheet somewhere beforehand?

Conditional codes in html template

Hi @ampedandwired,

Is it possible to have conditional codes, something like below:

if (o.webpackconfig.Production)
{
 <script type="text/javascript" src="{%=o.webpackconfig.UrlInProduction %}"></script>
}
else{
 <script type="text/javascript" src="{%=o.webpackconfig.urlInDevelopment%}"></script>
}

thanks

Cannot read undefined

I am stuck with this error when I try the default template:

nction(s,d){_s+=tmpl(s,d);},_s='<html'; if(o.htmlWebpackPlugin.files.manifest)
                                                                    ^
TypeError: Cannot read property 'manifest' of undefined
    at eval (eval at <anonymous> (/Users/jasonkuhrt/projects/react-popover/node_modules/html-webpack-plugin/node_modules/blueimp-tmpl/js/tmpl.js:26:65), <anonymous>:1:147)
    at tmpl (/Users/jasonkuhrt/projects/react-popover/node_modules/html-webpack-plugin/node_modules/blueimp-tmpl/js/tmpl.js:29:23)
    at HtmlWebpackPlugin.emitHtml (/Users/jasonkuhrt/projects/react-popover/node_modules/html-webpack-plugin/index.js:46:14)
    at /Users/jasonkuhrt/projects/react-popover/node_modules/html-webpack-plugin/index.js:37:16
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:379:3)

1.5.1 to NPM

Mind pushing the latest to NPM with the manifest fix? Thanks!

webpack external script tags, automatically

Suppose one uses react or jquery, then it's good idea (sometimes) to use this externals feature of webpack:

webpack.config.js

module.exports = {
    // ...
    externals: {
        "react" : "React"
    }
};

For instance, my index.js went from 640kB to 4kB. With that one line! Yes I know I must include a <script /> tag for react & assume React global does not clash. But it's nicer way sometimes.

It would be cool if HtmlWebpackPlugin had a way to inject those externals almost automatically. Even this would be a improvement:

package.json

{
  "dependencies": {
    "react": "0.13.2"
  },
  "external-scripts" : {
    "react" : "https://cdnjs.cloudflare.com/ajax/libs/react/0.13.2/react.min.js"
  }
}

Notice that I intentionally would like to put my external script URLs in package.json because it includes version numbers already.

Vendor files

Hi,

We are using vendor files which rarely change (twice a month),
We need them to load before our application code.
Is that possible ?

Taking from default_index.html:

    {% for (var chunk in o.htmlWebpackPlugin.assets) { %}
    <script src="{%=o.htmlWebpackPlugin.assets[chunk]%}"></script>
    {% } %}

loads all the files without order.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.