问题
I am using webpack-dev-server in a very simple setup.
I've found that even though the server automatically triggers a browser reload when the index.js file changes, it does not trigger a reload when the index.html changes. How can I achieve that?
Here's my setup:
package.json
{
"name": "html-reload",
"version": "1.0.0",
"description": "",
"main": "src/index.js",
"scripts": {
"build": "node_modules/webpack/bin/webpack.js",
"start": "webpack-dev-server --host 0.0.0.0 --port 8383 --content-base dist"
},
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^1.12.14",
"webpack-dev-server": "^1.14.1"
}
}
webpack.config.js
module.exports = {
entry: './src/index.js',
output: {
path: 'dist',
filename: 'bundle.js'
}
};
I launch the webpack-dev-server with: npm run start and I point my browser to:
http://localhost:8383/webpack-dev-server/index.html
Every change I made in src/index.js is automatically refreshed in the browser, but not so with changes I make in dist/index.html.
回答1:
I finally stumbled across html-webpack-plugin as described in this guide.
I run:
npm i -D html-webpack-plugin
And edited my webpack.config.js to look like this:
'use strict';
const path = require('path');
const APPDIR = 'app/';
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: path.resolve(__dirname, APPDIR, 'index.html'),
filename: 'index.html',
inject: 'body'
});
const config = {
context: path.resolve(__dirname, APPDIR),
entry: './main.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
include: path.resolve(__dirname, 'app/')
},{
test: /\.css$/,
loaders: ['style', 'css']
}
]
},
plugins: [HTMLWebpackPluginConfig]
};
module.exports = config;
The "template" index.html file now resides in my app directory and upon building the project a generated index.html file is placed in the build directory. The latter file contains the correct reference to the bundled output file bundle.js (this is the only difference between the two files).
"Template" index.html file in app:
<!doctype html>
<html>
<head>
<script src="http://localhost:8090/webpack-dev-server.js"></script>
</head>
<body>
<div id='app'></div>
</body>
</html>
Generated output index.html file in build:
<!doctype html>
<html>
<head>
<script src="http://localhost:8090/webpack-dev-server.js"></script>
</head>
<body>
<div id='app'></div>
<script type="text/javascript" src="bundle.js"></script></body>
</html>
Now, when running webpack-dev-server changes to index.html are also immediately refreshed in the browser.
This being said, the index.html being so minimal, the use case for editing it and wanting the edits to automatically refresh the browser seems trivial.
Nevertheless, it feels better that index.html resides in my app directory as opposed to the build directory.
来源:https://stackoverflow.com/questions/35842455/browser-automatic-reload-when-index-html-changes