Asset Injector (Webpack plugin)
Simply inject CSS and JavaScript assets into HTML assets with Webpack
Asset Injector is a simple, lightweight way to put <link>
and <script>
tags where you want them in your HTML files. When such a basic task is what you need, something like HTML Webpack Plugin can be overkill and needlessly balloon your build time.
Installation
$ npm install asset-injector-webpack-plugin --save-dev
Basic Usage
Asset Injector replaces structured comments in HTML files with <link>
and/or <script>
tags that reference the compiled asset(s) for a given chunk name.
webpack.config.js
... const asset_injector = ; ... webpack_configentry = index: './index.js' 'index.css': './index.css' 'index.html': './index.html' ; ... const Commons_chunk = webpackoptimizeCommonsChunkPlugin;webpack_configplugins = name: 'lib' minChunks: is_from_npm name: 'liaison' minChunks: Infinity // sometimes called "manifest" ; ... { return modulecontext && -1 !== modulecontext;} ...
index.html
App <!-- asset-injector index.css --> <!-- asset-injector liaison --> <!-- asset-injector lib --> <!-- asset-injector index -->
Gotchas
Because it is not always obvious what assets Webpack will output for a given chunk, Asset Injector seeks to be lenient while specific.
For the index.css
entry point in the earlier example, <!-- asset-injector index.css -->
will be replaced with something like:
This is because all entry points result in a .js
file being output (and generally a .js.map
file too). To specify only the stylesheet, each of the following will only inject the <link>
tag:
<!-- asset-injector style index.css --><!-- asset-injector styles index.css --><!-- asset-injector stylesheet index.css --><!-- asset-injector-plugin style index.css --><!-- asset-injector-webpack-plugin styles index.css --><!-- asset_injector_webpack_plugin stylesheet index.css -->
The same is true for <script>
tags:
<!-- asset-injector script lib --><!-- asset-injector scripts lib -->
And because it is also not always obvious what Webpack chunks' names are, Asset Injector attempts to figure out what you intended if a chunk name isn't found. For example, simple mistakes like the following will do what you expect:
<!-- asset-injector lib.js -->
will work if the chunk name is technically lib
<!-- asset-injector styles.css -->
will work if the chunk name is technically styles.scss
(SASS file) or styles