本文详细介绍webpack-dev-server的安装与基本用法,涵盖命令行启动、目录设置及两种自动刷新模式(iframe与inline)。重点讲解如何配置Hot Module Replacement(HMR)以实现热模块替换,包括命令行与Node.js API两种启动方式的具体配置步骤,帮助开发者提升前端开发效率。
webpack-dev-server 简介与安装
webpack-dev-server
webpack-dev-server 是一个基于 Node.js 和 Express 构建的小型服务器。它利用 webpack-dev-middleware 中间件来提供 webpack 打包后的资源服务,同时内置了一个通过 Sock.js 与服务器通信的微型运行时环境。
接下来查看一个典型的配置文件示例(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"
}
}
在该配置中,源文件存放于 app 文件夹下,通过 webpack 打包后输出至 build 文件夹中的 bundle.js 文件。
注意:webpack-dev-server 是一个独立的 NPM 包,你可以通过执行 npm install webpack-dev-server 命令来安装它。
基本目录与访问方式
基本目录设置
默认情况下,webpack-dev-server 会以当前工作目录作为根目录,除非你手动指定其他路径。
webpack-dev-server --content-base build/
上述命令是在命令行中执行的,它将 build 目录指定为内容根目录。需要特别注意的是:webpack-dev-server 生成的打包文件并未实际写入你的物理磁盘目录,而是存储在内存中。
我们在基本目录下新建一个 index.html 文件,然后在浏览器地址栏输入 http://localhost:8080 即可访问。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="assets/bundle.js"></script>
</body>
</html>
自动刷新模式:iframe 与 inline
自动刷新功能
webpack-dev-server 支持两种模式来实现页面的自动刷新。
- iframe 模式:页面被嵌入在 iframe 中,当代码发生变化时,iframe 会自动重载。
- inline 模式:将 webpack-dev-server 的客户端入口脚本注入到打包文件(bundle)中。
这两种模式均支持热模块替换(Hot Module Replacement,简称 HMR)。HMR 的优势在于仅替换发生更新的模块,而无需重新加载整个页面,从而保持应用状态。
iframe 模式
使用这种模式无需额外配置,只需按照以下 URL 格式进行访问即可。
例如:http://localhost:8080/webpack-dev-server/index.html。
inline 模式
在 inline 模式下,访问的 URL 无需改变。启用该模式分为两种情况:
1. 当通过命令行启动 webpack-dev-server 时,需要执行以下两个操作:
- 在命令行参数中添加 --inline 选项。
- 在 webpack.config.js 配置文件中添加 devServer: {inline: true}。
2. 当通过 Node.js API 启动 webpack-dev-server 时,同样需要执行两个操作:
- 由于 webpack-dev-server 的配置对象中没有 inline 选项,我们需要在 webpack 配置的 entry 入口点中添加 webpack-dev-server/client?http://«path»:«port/”。
- 在 html 文件中添加 <script src="http://localhost:8080/webpack-dev-server.js"></script> 脚本标签。
var config = require("./webpack.config.js");
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
config.entry.app.unshift("webpack-dev-server/client?http://localhost:8080/");
var compiler = webpack(config);
var server = new WebpackDevServer(compiler, {
contentBase:'build/',
publicPath: "/assets/"
});
server.listen(8080);
在 Node 环境中运行上述代码即可生效。
注意:webpack 配置中的 devServer 配置项仅对命令行启动模式有效。
热模块替换(HMR)配置详解
(Hot Module Replacement)热模块替换配置
在命令行中运行 inline 模式,并启用热模块替换功能。
只需在命令行中额外增加 --hot 指令即可,示例如下。
webpack-dev-server --content-base build --inline --hot
注意:在命令行模式下,webpack.config.js 中必须配置 output.publicPath 来指定编译后包(bundle)的访问路径。
在 Node.js API 中运行 inline 模式,并启用热模块替换。
此时需要进行以下三项配置:
- 在 webpack.config.js 的 entry 选项中添加:webpack/hot/dev-server。
- 在 webpack.config.js 的 plugins 选项中添加:new webpack.HotModuleReplacementPlugin()。
- 在 webpack-dev-server 的配置对象中添加:hot: true。
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 'http://localhost:8080/' 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('/some/path', function(req, res) {
// res.json({ custom: 'response' });
// });
},
// 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's a required option.
publicPath: "/assets/",
headers: { "X-Custom-Header": "yes" },
stats: { colors: true }
});
server.listen(8080, "localhost", function() {});
// server.close();
更多详细信息可参考:http://webpack.github.io/docs/webpack-dev-server.html
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。