search
HomeWeb Front-endJS TutorialDetailed explanation of the simple use of webpack-dev-server_javascript skills

This article mainly introduces the simple use of webpack-dev-server in detail. Now I will share it with you and give you a reference. Let’s follow the editor to take a look

webpack-dev-server

webpack-dev-server is a small Node.js Express server. Use webpack-dev-middleware to serve webpack packages. In addition, it also has a micro runtime that connects to the server through Sock.js.

Let’s take a look at the following configuration file ( webpack.config.js)

var path = require("path");
module.exports = {
 entry:{
 app:["./app/main.js"]
 },
 output:{
 path:path.resolve(__dirname,"build"),
 publicPath:"/assets/",
 filename:"bundle.js"
}
}

Here you put your source files in the app folder and package them into the build folder through webpack bundle.js.

Note: webpack-dev-server is an independent NPM package, you can install it through npm install webpack-dev-server.

Basic Directory

webpack-dev-server defaults to the current directory as the base directory unless you specify it.

webpack-dev-server --content-base build/

The above command is executed in the command line, which takes the build directory as the root directory. One thing to note is that the package generated by webpack-dev-server is not placed in your real directory, but in memory.中.

We create a new index.html file in the basic directory, and then enter http://localhost:8080 in the browser to access.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
</head>
<body>
 <script src="assets/bundle.js"></script>
</body>
</html>

Auto-refresh

webpack-dev-server supports two modes to automatically refresh the page.

  1. iframe mode ( The page is placed in an iframe and reloaded when changes occur)

  2. inline mode (add the client entry of webpack-dev-sever to the bundle)

Both modes support Hot Module Replacement. The advantage of hot module replacement is that only the updated part is replaced instead of page reloading.

iframe mode
No additional configuration is required to use this mode, you only need to access it in the following URL format

http://«host»:«port»/webpack-dev-server/«path»

For example: http://localhost:8080/webpack-dev-server/index.html.

inline mode

The URL we access does not need to change in inline mode. There are two situations when enabling this mode:

1 When starting webpack-dev-server from the command line, two things need to be done:

  1. Add the --inline command to the command line

  2. Add devServer:{inline:true} to webpack.config.js

2 When starting webpack-dev-server with Node.js API, we also need to do two things:

  1. Since there is no inline in the configuration of webpack-dev-server option, we need to add webpack-dev-server/client?http://«path»:«port»/ to the entry entry point of the webpack configuration.

  2. Replace Add to html file

 var config = require("./webpack.config.js");
 var webpack = require(&#39;webpack&#39;);
 var WebpackDevServer = require(&#39;webpack-dev-server&#39;);

config.entry.app.unshift("webpack-dev-server/client?http://localhost:8080/");

var compiler = webpack(config);
var server = new WebpackDevServer(compiler, {
 contentBase:&#39;build/&#39;,
 publicPath: "/assets/"
});
server.listen(8080);

Just run the above code in Node.

Note: The devSever configuration item in the webpack configuration is only valid in the command line mode.

(Hot Module Replacement) Hot module replacement

Run inline mode in the command line and enable hot module replacement

You only need to add more --hot instructions here and it will be OK. As shown below.

webpack-dev-server --content-base build --inline --hot

Note: In command line mode, in webpack.config.js Be sure to configure output.publicPath to specify the access location of the compiled package (bundle).

Run inline mode in Nodejs API and enable hot module replacement

What you need to do here The following three points:

  1. Add in the entry option of webpack.config.js: webpack/hot/dev-server

  2. in webpack. Add to the plugins option of config.js: new webpack.HotModuleReplacementPlugin()

  3. Add to the configuration of webpack-dev-server: hot:true

Configuration options in webpack-dev-server

var WebpackDevServer = require("webpack-dev-server");
var webpack = require("webpack");

var compiler = webpack({
 // configuration
});
var server = new WebpackDevServer(compiler, {
 // webpack-dev-server options

 contentBase: "/path/to/directory",
 // Can also be an array, or: contentBase: "http://localhost/",

 hot: true,
 // Enable special support for Hot Module Replacement
 // Page is no longer updated, but a "webpackHotUpdate" message is send to the content
 // Use "webpack/hot/dev-server" as additional module in your entry point
 // Note: this does _not_ add the `HotModuleReplacementPlugin` like the CLI option does. 

 // Set this as true if you want to access dev server from arbitrary url.
 // This is handy if you are using a html5 router.
 historyApiFallback: false,

 // Set this if you want to enable gzip compression for assets
 compress: true,

 // Set this if you want webpack-dev-server to delegate a single path to an arbitrary server.
 // Use "**" to proxy all paths to the specified server.
 // This is useful if you want to get rid of &#39;http://localhost:8080/&#39; in script[src],
 // and has many other use cases (see https://github.com/webpack/webpack-dev-server/pull/127 ).
 proxy: {
 "**": "http://localhost:9090"
 },

 setup: function(app) {
 // Here you can access the Express app object and add your own custom middleware to it.
 // For example, to define custom handlers for some paths:
 // app.get(&#39;/some/path&#39;, function(req, res) {
 // res.json({ custom: &#39;response&#39; });
 // });
 },

 // pass [static options](http://expressjs.com/en/4x/api.html#express.static) to inner express server
 staticOptions: {
 },

 // webpack-dev-middleware options
 quiet: false,
 noInfo: false,
 lazy: true,
 filename: "bundle.js",
 watchOptions: {
 aggregateTimeout: 300,
 poll: 1000
 },
 // It&#39;s a required option.
 publicPath: "/assets/",
 headers: { "X-Custom-Header": "yes" },
 stats: { colors: true }
});
server.listen(8080, "localhost", function() {});
// server.close();

Reference: http://webpack.github.io/docs/webpack- dev-server.html

Related recommendations:

How to set remote mode for webpack-dev-server

Detailed explanation of webpack-dev-server using http-proxy to solve cross-domain problems

The above is the detailed content of Detailed explanation of the simple use of webpack-dev-server_javascript skills. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version