Using webpack-dev-server
suggest changeSetup
After setting up a simple project to use webpack, Babel, and React, run npm i -g webpack-dev-server to install the development HTTP server. A local dev dependency is easier to reproduce than a global install.
Modifying webpack.config.js
var path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'out'),
publicPath: '/public/',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
},
devServer: {
contentBase: path.resolve(__dirname, 'public'),
hot: true
}
};
The modifications are in
output.publicPathwhich sets up a path to have our bundle be served from (see Webpack configuration files for more info)devServercontentBaseis the base path for static files (for exampleindex.html)hotturns on hot reload when files change. You also needwebpack.HotModuleReplacementPlugin;hot: truealone does not install that plugin.
And finally we just need a simple index.html to test our app in.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>React Sandbox</title>
</head>
<body>
<div id="app"></div>
<script src="/public/bundle.js"></script>
</body>
</html>
With this setup, running webpack-dev-server should start a local HTTP server on port 8080. If src/index.js is the Hello World from the simple setup, the page renders <h1>Hello world!</h1>. Put index.html in the public/ folder named by contentBase. The script URL uses output.publicPath.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents