- Progressive Web Apps with React
- Scott Domes
- 395字
- 2021-07-08 09:36:18
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.
- Visual C++程序設計教程
- Mastering phpMyAdmin 3.4 for Effective MySQL Management
- Scala Design Patterns
- PHP+MySQL網站開發技術項目式教程(第2版)
- 深入淺出Android Jetpack
- 算法訓練營:提高篇(全彩版)
- Mathematica Data Analysis
- Python時間序列預測
- Python算法詳解
- Internet of Things with ESP8266
- 零基礎C#學習筆記
- Drupal 8 Development:Beginner's Guide(Second Edition)
- Building UIs with Wijmo
- Visual FoxPro程序設計實驗教程
- 趣學數據結構