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

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.

主站蜘蛛池模板: 青神县| 如东县| 翼城县| 兴义市| 奎屯市| 搜索| 巫溪县| 乳源| 离岛区| 吴堡县| 永平县| 曲阜市| 龙泉市| 锡林郭勒盟| 关岭| 德令哈市| 福贡县| 响水县| 井陉县| 平顶山市| 鹰潭市| 泰宁县| 申扎县| 长治县| 汶上县| 平安县| 杨浦区| 萨嘎县| 桓仁| 平舆县| 贡觉县| 绥江县| 宜兴市| 仙桃市| 南华县| 大姚县| 秭归县| 平乐县| 皋兰县| 体育| 垣曲县|