Skip to content

Easy and powerful way to add ext attributes to tag with html-webpack-plugin

License

Notifications You must be signed in to change notification settings

dyw934854565/html-webpack-inject-attributes-plugin

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

html-webpack-inject-attributes-plugin

NPM Version Dependency Status Build Status Download Status MIT License

add custom attributes to inject tags

install

npm install html-webpack-inject-attributes-plugin -D

use

please use it after html-webpack-plugin, especially in webpack2+.

add to all inject tags, effective in all html

    plugins = [
        new HtmlWebpackPlugin(),
        new htmlWebpackInjectAttributesPlugin({
            inject: "true",
            async: true,
            test: {}
        })  // Object, key should be string, value can be string or function、object, object will stringify
    ]

you got

    <script type="text/javascript" src="index.js" inject="true" async test="{}"></script>

add to chunks in HtmlWebpackPlugin by add attributes to HtmlWebpackPlugin,only effective in the current html

    plugins = [
        new HtmlWebpackPlugin({
            attributes: {
                'data-src': function (tag) { return tag.attributes.src }
            },
        }),
        new htmlWebpackInjectAttributesPlugin()
    ]
    /**
     *  if value is a function, got three arguments。
     *  1、tag, ast of tag node
     *  2、compilation, you can get webpack build hash by compilation.hash
     *  3、index, index of trunks
    **/

you got

    <script type="text/javascript" src="index.js" data-src="index.js" inject="true"></script>

return false to prevent some tags add attributes

    plugins = [
        new HtmlWebpackPlugin({
            inject: true,
            hash: true,
            chunks: ['index'],
            attributes: {
                'data-src': function (tag, compilation, index) {
                    if (tag.tagName === 'script') {
                        return true;
                    }
                    return false;
                }
            },
        }),
        new htmlWebpackInjectAttributesPlugin()
    ]

style tags do not be affected

use chainWebpack

// vue.config.js
const htmlInject = require('html-webpack-inject-attributes-plugin')
module.exports = {
  chainWebpack: (config) => {
    config.plugin('html')
      .tap(args => {
        args[0].attributes = {
          async: true,
          inject: 'true'
        }
        return args
      })

    config.plugin('html-inject')
      .after('html')
      .use(htmlInject, [{
          common: 'true'
      }])
  },
}

LICENSE

MIT License

About

Easy and powerful way to add ext attributes to tag with html-webpack-plugin

Resources

License

Stars

Watchers

Forks

Packages

No packages published