React Setup, Part IV: HTMLWebpackPlugin
Configure HTMLWebpackPlugin on your Local Computer
HTMLWebpackPlugin
Good work! The hardest part is over. There is, however, still one issue.
Your app’s main HTML file is named app/index.html. Your app’s outermost JavaScript file, which is also your entry point for webpack, is named app/index.js. These two files are neighbors, both living in the app
folder.
Before webpack performs its transformations, your entry file (app/index.js) and your HTML file (app/index.html) are located in the same directory. The HTML file contains a link to the entry file, looking something like this: <script src="./index.js"></script>
.
After webpack performs its transformations, your new entry file will be located in build/transformed.js, and that link won’t work anymore!
When webpack makes a new JavaScript file, it needs to make a new HTML file as well. There is a tool for this, and you’ve already installed it: html-webpack-plugin
.
Configure HTMLWebpackPlugin
At the top of webpack.config.js, add this line of code:
When you call require('html-webpack-plugin')
, the returned value is a constructor function. Most of the work of configuring HTMLWebpackPlugin should be done on an instance of that constructor function.
Add this new declaration, underneath the previous one:
The HTMLWebpackPlugin Configuration Object
That empty configuration object is where you will tell HTMLWebpackPlugin what it needs to know.
The object’s first property should be named template
. template
‘s value should be a filepath to the current HTML file, the one that you’re trying to copy and move:
The object’s second property should be named filename
. filename
‘s value should be the name of the newly created HTML file. It’s fine to name it index.html
. Since the new HTML file will be located in the build folder, there won’t be any naming conflicts:
The object’s final property should be named inject
. inject
value should be be a string: either 'head'
or 'body'
.
When HTMLWebpackPlugin creates a new HTML file, that new HTML file will contain a <script>
tag linking to webpack’s new JavaScript file. This <script>
tag can appear in either the HTML file’s <head>
or <body>
. You choose which one via the inject
property.
Here’s an full example:
The Plugins Property
You have fully configured your HTMLWebpackPlugin
instance! Now all that’s left is to add that instance to module.exports
.
You can do this by creating a new module.exports
property named plugins
. plugins
value should be an array, containing your configured HTMLWebpackPlugin
instance!
Find the plugins
property at the bottom of module.exports
:
Whenever you’re ready, continue to our final article!