JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 42114
  • Score
    100M100P100Q154627F
  • License MIT

lets you define html tags to inject with html-webpack-plugin

Package Exports

  • html-webpack-tags-plugin

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (html-webpack-tags-plugin) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Tags Plugin for the HTML Webpack Plugin

npm version Build Status js-semistandard-style

Enhances html-webpack-plugin by letting you specify script or link tags to inject.

Prior Version

Motivation

When using a plugin such as copy-webpack-plugin you may have assets output to your build directory that are not detected/output by the html-webpack-plugin.

This plugin lets you manually resolve such issues, and also lets you inject the webpack publicPath or compilation hash into your tag asset paths if you so choose.

Installation

You must be running webpack on node 8.x or higher

Install the plugin with npm:

$ npm install --save-dev html-webpack-tags-plugin

Basic Usage

Require the plugin in your webpack config:

var HtmlWebpackTagsPlugin = require('html-webpack-tags-plugin');

Add the plugin to your webpack config:

output: {
  publicPath: '/abc/'
},
plugins: [
  new HtmlWebpackPlugin(),
  new HtmlWebpackTagsPlugin({ tags: ['a.js', 'b.css'], append: true })
]

Which will generate html like this:

<head>
  <!-- other head content -->
  <link rel="stylesheet" href="/abc/b.css"/>
</head>
<body>
  <!-- other body content -->
  <script type="text/javascript" src="/abc/a.js"></script>
</body>

Options

The available options are:

  • jsExtensions:string|array - The file extensions to use when attempting to determine if a tag object is a script.

  • cssExtensions:string|array - The file extensions to use when attempting to determine if a tag object is a link.

  • append:boolean - Use true to append tags or false to prepend tags.

  • publicPath: boolean or string, or function(path:string, publicPath:string) => any:string - (default true)

    • Determines whether the tag assets should be prepended with webpack's public path or a custom publicPath (string or function).

    • A value of false may be used to disable prefixing with webpack's publicPath, or a value like myPublicPath/ may be used to prefix all tag assets with the given string. Default is true.

  • hash: boolean or function(path: string, hash: string) => any: string - (default false)

    Specifying whether the tag assets should be appended with webpack's compilation hash. This is useful for cache busting. Default is false.

  • files: string or array - (default [])

    Files that the tags will be added to. Using this option can be necessary if you are using multiple instances of the this plugin or html-webpack-plugin plugin instances.

    By default the tags will be injected in all files. If files are defined, the tags will only be injected in specified file globs (uses the minimatch package).

  • links:string|array|object - (default []) - Shortcut to add tags that are all type css. Will be added after any tags values.

  • scripts:string|array|object - (default []) - Shortcut to add tags that are all type js. Will be added after any tags values.

  • tags:string|array|object - (default [])

    Tags that will be output into your html-webpack-plugin template.

    • To specify just one tag asset, simply pass a string or object.
    • To specify multiple tag assets, pass an array of strings or objects.

    Tags that do not have a type attempt to infer it from the asset path using the jsExtensions and cssExtensions options values.

    This plugin will throw an error if it cannot determine the type of any tag, we can specify tags as objects to fix that.

    const oldTag = 'abc'; // change this
    
    const newTag = { // to this
      path: 'abc',
      type: 'css'
    }

    Each tag object may have the following properties:


  • path:string (required) - The tag path.
  • type:string (optional) - For tags where the type is unknown, this can be set to either of: ['css', 'js'].
  • glob:string and globPath:string (must be together) - Lets you use a glob to insert multiple tags from the globPath.
  • attributes:object (optional) - The attributes to be injected into the html tags. Some attributes are filtered by html-webpack-plugin (especially for script tags). To work requires that you set the html-webpack-plugin options to: { inject: true }.
  • sourcePath:string (optional) - property may be used to specify a source path to be added as an entry to html-webpack-plugin. This can be useful as it will trigger a recompilation after the assets have changed when using webpack-dev-server or webpack-dev-middleware in development mode.
  • publicPath:boolean|function(path:string, publicPath:string) => any:string (optional) - Controls whether the webpack publicPath will be injected into the asset path. true mean always. false means never. function means manual, undefined means use global settings.
  • hash:boolean|function(path:string, hash:string) => any:string (optional) - Controls whether the webpack compilation hash will be injected into the asset path. true mean always. false means never. function means manual, undefined means use global settings.
  • external:object({ packageName:string, variableName:string }) (only for script tags) - When specified together cause { packageName: variableName } to be added to webpack config's externals.

Examples


Using HtmlWebpackTagsPlugin and CopyWebpackPlugin to inject asset tags into html-webpack-plugin template :

plugins: [
  new CopyWebpackPlugin([
    { from: 'node_modules/bootstrap/dist/css', to: 'css/'},
    { from: 'node_modules/bootstrap/dist/fonts', to: 'fonts/'}
  ]),
  new HtmlWebpackPlugin(),
  new HtmlWebpackTagsPlugin({
    tags: ['css/bootstrap.min.css', 'css/bootstrap-theme.min.css'],
    append: false
  })
]

Appending and prepending at the same time :

plugins: [
  new CopyWebpackPlugin([
    { from: 'node_modules/bootstrap/dist/css', to: 'css/'},
    { from: 'node_modules/bootstrap/dist/fonts', to: 'fonts/'}
  ]),
  new HtmlWebpackPlugin(),
  new HtmlWebpackTagsPlugin({
    tags: ['css/bootstrap.min.css', 'css/bootstrap-theme.min.css'],
    append: false
  }),
  new HtmlWebpackTagsPlugin({
    tags: ['css/custom.css'],
    append: true
  })
]

Using custom jsExtensions :

plugins: [
  new HtmlWebpackPlugin(),
  new HtmlWebpackTagsPlugin({
    tags: ['dist/output.js', 'lib/content.jsx'],
    append: false,
    jsExtensions: ['.js', '.jsx']
  })
]

Using custom publicPath :

plugins: [
  new CopyWebpackPlugin([
    { from: 'node_modules/bootstrap/dist/css', to: 'css/'},
    { from: 'node_modules/bootstrap/dist/fonts', to: 'fonts/'}
  ]),
  new HtmlWebpackPlugin(),
  new HtmlWebpackTagsPlugin({
    tags: ['css/bootstrap.min.css', 'css/bootstrap-theme.min.css'],
    append: false,
    publicPath: 'myPublicPath/'
  })
]

Or to include tag assets without prepending the publicPath:

plugins: [
  new HtmlWebpackPlugin(),
  new HtmlWebpackTagsPlugin({
    tags: ['css/no-public-path.min.css', 'http://some.domain.com.js'],
    append: false,
    publicPath: false
  })
]

Manually specifying asset types :

plugins: [
  new CopyWebpackPlugin([
    { from: 'node_modules/bootstrap/dist/css', to: 'css/'},
    { from: 'node_modules/bootstrap/dist/fonts', to: 'fonts/'}
  ]),
  new HtmlWebpackPlugin(),
  new HtmlWebpackTagsPlugin({
    tags: [
      '/css/bootstrap.min.css',
      '/css/bootstrap-theme.min.css',
      { path: 'https://fonts.googleapis.com/css?family=Material+Icons', type: 'css' }
    ],
    append: false,
    publicPath: ''
  })
]

Adding custom attributes to asset tags :

The bootstrap-theme link tag will be given an id="bootstrapTheme" attribute.

plugins: [
  new CopyWebpackPlugin([
    { from: 'node_modules/bootstrap/dist/css', to: 'css/'},
    { from: 'node_modules/bootstrap/dist/fonts', to: 'fonts/'}
  ]),
  new HtmlWebpackPlugin(),
  new HtmlWebpackTagsPlugin({
    tags: [
      '/css/bootstrap.min.css',
      { path: '/css/bootstrap-theme.min.css', attributes: { id: 'bootstrapTheme' } }
    ],
    append: false,
    publicPath: ''
  })
]

Using hash option :

When the hash option is set to true, asset paths will be appended with a hash query parameter (?hash=<the_hash>)

plugins: [
  new CopyWebpackPlugin([
    { from: 'node_modules/bootstrap/dist/css', to: 'css/'},
    { from: 'node_modules/bootstrap/dist/fonts', to: 'fonts/'}
  ]),
  new HtmlWebpackPlugin(),
  new HtmlWebpackTagsPlugin({
    tags: ['css/bootstrap.min.css', 'css/bootstrap-theme.min.css'],
    append: false,
    hash: true
  })
]

When the hash option is set to a function, asset paths will be replaced with the result of executing that function

plugins: [
  new CopyWebpackPlugin([
    { from: 'somepath/somejsfile.js', to: 'js/somejsfile.[hash].js' },
    { from: 'somepath/somecssfile.css', to: 'css/somecssfile.[hash].css' }
  ]),
  new HtmlWebpackPlugin(),
  new HtmlWebpackTagsPlugin({
    tags: [{ path: 'js', glob: '*.js', globPath: 'somepath' }],
    tags: [{ path: 'css', glob: '*.css', globPath: 'somepath' }],
    append: false,
    hash: function(assetName, hash) {
      assetName = assetName.replace(/\.js$/, '.' + hash + '.js');
      assetName = assetName.replace(/\.css$/, '.' + hash + '.css');
      return assetName;
    }
  })
]

Specifying specific files

plugins: [
  new CopyWebpackPlugin([
    { from: 'node_modules/bootstrap/dist/css', to: 'css/'},
    { from: 'node_modules/bootstrap/dist/fonts', to: 'fonts/'}
  ]),
  new HtmlWebpackPlugin({
    filename: 'a/index.html'
  }),
  new HtmlWebpackPlugin({
    filename: 'b/index.html'
  }),
  new HtmlWebpackTagsPlugin({
    files: ['a/**/*.html'],
    tags: ['css/a.css'],
    append: true
  }),
  new HtmlWebpackTagsPlugin({
    files: ['b/**/*.html'],
    tags: ['css/b.css'],
    append: true
  })
]

Specifying tag assets usings a glob

Note that since copy-webpack-plugin does not actually copy the files to webpack's output directory until after html-webpack-plugin has completed, it is necessary to use the globPath to retrieve filename matches relative to the original location of any such files.

plugins: [
  new CopyWebpackPlugin([
    { from: 'node_modules/bootstrap/dist/css', to: 'css/'},
    { from: 'node_modules/bootstrap/dist/fonts', to: 'fonts/'}
  ]),
  new HtmlWebpackPlugin(),
  new HtmlWebpackTagsPlugin({
    tags: [{ path: 'css', glob: '*.css', globPath: 'node_modules/bootstrap/dist/css/' }],
    append: true
  })
]

Specifying links (a shortcut for specifying link vs script tags)

output: {
  publicPath: '/my-public-path/'
},
plugins: [
  new CopyWebpackPlugin([
    { from: 'node_modules/bootstrap/dist/css', to: 'css/'},
    { from: 'node_modules/bootstrap/dist/fonts', to: 'fonts/'}
  ]),
  new HtmlWebpackPlugin(),
  new HtmlWebpackTagsPlugin({
    tags: [],
    append: true,
    links: [
      {
        href: 'asset/path',
        attributes: {
          rel: 'icon'
        }
      },
      {
        href: '/absolute/asset/path',
        asset: false,
        attributes: {
          rel: 'manifest'
        }
      }
    ]
  })
]

Will append the following link elements into the index template html

<head>
  <!-- previous header content -->
  <link rel="icon" href="/my-public-path/asset/path"/>
  <link rel="manifest" href="/absolute/asset/path"/>
</head>

Note that the second link's href was not prefixed with the webpack publicPath because csAsset.asset was set to false.


Caveats

Some users have encountered issues with plugin ordering.

  • It is advisable to always place any HtmlWebpackPlugin plugins before any HtmlWebpackTagsPlugin plugins in your webpack config.

This plugin has only been tested with two instances in one webpack config, where one had option.append: false and the other had option.append: true.

  • It is not recommended to use more than one instance of this plugin in one webpack config unless using the above configuration.

Changing HtmlWebpackPlugin.options.inject from its default value may cause issues.

  • This plugin requires HtmlWebpackPlugin.options.inject to be true (it defaults to true if undefined) for attribute injection to work.

If you setup your webpack config to have HtmlWebpackPlugin.options.inject: false like this:

output: {
  publicPath: '/the-public-path/'
},
plugins: [
  new HtmlWebpackPlugin({ inject: false }),
  new HtmlWebpackTagsPlugin({
    tags: [{ path: 'css/bootstrap-theme.min.css', attributes: { id: 'bootstrapTheme' } }],
    links: [{ href: 'the-ref', attributes: { rel: 'icon' } }],
    append: true
  })
]

You will need to add the following to your template index.html to get tags to be generated:

<head>
  <!-- other head content -->
  <% for (var cssIndex = 0; cssIndex < htmlWebpackPlugin.files.css.length; cssIndex++) { %>
    <link rel="stylesheet" href="<%= htmlWebpackPlugin.files.css[cssIndex] %>">
  <% } %>
</head>
<body>
  <!-- other body content -->
  <% for (var jsIndex = 0; jsIndex < htmlWebpackPlugin.files.js.length; jsIndex++) { %>
    <script src="<%= htmlWebpackPlugin.files.js[jsIndex] %>"></script>
  <% } %>
</body>

Using the (lodash) template syntax like this for css and js files is necessary when you turn injection off.

But, the template syntax does not allow injection of more than one attribute value.

This means it will generate an index.html that looks like this:

<head>
  <link rel="stylesheet" href="/the-public-path/css/bootstrap-theme.min.css">
  <link rel="stylesheet" href="/the-public-path/the-ref">
</head>

None of the link elements have any of the attributes we specified for the tags or links.

This is because HtmlWebpackPlugin.options.inject needs to be set to true for attributes injection to work.