官术网_书友最值得收藏!

Our Dev server

If we want to update our code (say, to change our h1 to h2), we’ll have to make the change, rerun yarn build, and then reload the page for every single change we want to see. That’ll slow us down a lot in our development process.

Ideally, every time we change our JavaScript, the Webpack command will automatically rerun, and will reload the page. What a world of luxury that would be!

Fortunately, there’s a package called webpack-dev-server for exactly this purpose. To install it, just run yarn add webpack-dev-server.

Before we jump in, let’s briefly cover how the Dev Server works. It runs a small Node application in the background of our machine, serving up the files in our public folder so that we can see them by visiting localhost:3000 in our browser. At the same time, it watches the source files of the bundle.js, rebundles them when they change, and then reloads the page.

To get it to work, we need to specify which folder we want to serve up (public), and then do some basic configuration.

In our webpack.config.js, add the following before the closing squiggly bracket (we have the full code here):

devServer: {
contentBase: "./public",
historyApiFallback: true,
inline: true,
}

contentBase does this, setting public as the folder to serve, historyApiFallback lets our single-page app seem like a multipage app, and inline is the bit that automatically refreshes the page on file changes:

module.exports = {
entry: __dirname + "/src/index.js",
output: {
path: __dirname + "/public",
filename: "bundle.js",
publicPath: "/"
},
devServer: {
contentBase: "./public",
historyApiFallback: true,
inline: true,
}
};

Okay, let’s try it. First, we’ll add a new script to our package.json, called start:

"scripts": {
"build": "node_modules/.bin/webpack",
"start": "node_modules/.bin/webpack-dev-server"
},

This will run our Dev Server (ensure that you ran yarn add webpack-dev-server first). In your Terminal, type in yarn start. You’ll see our Webpack compile, and a notice that our app is running on port 8080. Let’s hop over to http://localhost:8080 in our browser and we should see our application.

The last test is to change the text in our index.js from Hello from React to Hello from Webpack!. Your browser tab should automatically reload and reflect the changes, without you having to rerun the Webpack command.

主站蜘蛛池模板: 渭源县| 中阳县| 新安县| 兴和县| 定襄县| 金湖县| 清丰县| 鄱阳县| 宁海县| 巴彦淖尔市| 仁怀市| 中江县| 靖边县| 通榆县| 三明市| 句容市| 龙陵县| 南通市| 安达市| 澎湖县| 定西市| 如皋市| 怀化市| 卓尼县| 嵩明县| 宁海县| 望城县| 泸溪县| 邵武市| 库伦旗| 米林县| 六安市| 伊川县| 濉溪县| 启东市| 攀枝花市| 台江县| 东丰县| 黑山县| 会宁县| 漳州市|