Configuration and Usage of Webpack Dev Server
Webpack Dev Server is a local development server based on Express, specifically designed for Webpack projects. It provides features like Hot Module Replacement (HMR), automatic refresh, and request proxying, significantly improving development efficiency. Below is a step-by-step guide from configuration to usage.
Installing Webpack Dev Server
First, ensure that webpack
and webpack-cli
are installed in your project. If not, install them using the following command:
npm install webpack webpack-cli --save-dev
Next, install webpack-dev-server
:
npm install webpack-dev-server --save-dev
Basic Configuration
Configure the devServer
object in webpack.config.js
. Here’s a basic configuration example:
const path = require('path');
module.exports = {
// ...other configurations
devServer: {
static: {
directory: path.join(__dirname, 'dist'), // Static file directory
},
compress: true, // Enable gzip compression
port: 8080, // Specify the port
open: true, // Automatically open the browser
},
};
Hot Module Replacement (HMR)
HMR allows updating modules without refreshing the entire page. Enable it as follows:
module.exports = {
// ...other configurations
devServer: {
hot: true, // Enable HMR
},
};
Additionally, add HMR support code in the entry file:
if (module.hot) {
module.hot.accept('./app.js', () => {
console.log('Module hot-updated');
});
}
Proxy Configuration
During development, you may need to proxy API requests to a backend server. Configure this using proxy
:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000', // Backend address
pathRewrite: { '^/api': '' }, // Rewrite the path
changeOrigin: true, // Modify the host in the request header
},
},
},
};
Custom Middleware
Add custom Express middleware using setupMiddlewares
:
module.exports = {
devServer: {
setupMiddlewares: (middlewares, devServer) => {
if (!devServer) {
throw new Error('webpack-dev-server is not defined');
}
// Add custom middleware
middlewares.unshift({
name: 'logger',
path: '/log',
middleware: (req, res) => {
console.log('Request log:', req.url);
res.send('Log recorded');
},
});
return middlewares;
},
},
};
Development vs. Production Environment Separation
Typically, you’ll need a separate webpack.dev.js
for the development environment. Example:
const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.common.js');
module.exports = merge(commonConfig, {
mode: 'development',
devtool: 'eval-source-map',
devServer: {
// Development server configuration
},
});
Advanced Configuration Example
Combine historyApiFallback
and publicPath
for single-page application routing:
module.exports = {
devServer: {
historyApiFallback: {
rewrites: [
{ from: /^\/admin/, to: '/admin.html' },
{ from: /./, to: '/index.html' },
],
},
static: {
publicPath: '/assets/', // Static resource public path
},
},
};
Startup Script Configuration
Add a startup command in package.json
:
{
"scripts": {
"dev": "webpack serve --config webpack.dev.js"
}
}
Run npm run dev
to start the development server.
Common Issue Troubleshooting
-
Port Conflict: Modify
port
or specify via the--port
parameter:webpack serve --port 9000
-
HMR Not Working: Ensure the following conditions are met:
hot: true
is enabled in the configuration- HMR acceptance code is added to the entry file
- Use
webpack serve
instead of thewebpack-dev-server
command
-
Proxy Not Working: Ensure the
target
address is accessible and check if browser requests carry the correct prefix.
Performance Optimization Tips
-
Enable lazy compilation to improve startup speed:
module.exports = { devServer: { lazy: true, // Compile only when the corresponding resource is requested }, };
-
Limit recompilation scope:
module.exports = { watchOptions: { ignored: /node_modules/, // Ignore changes in node_modules }, };
-
Use
inline
mode to reduce resource loading time:module.exports = { devServer: { inline: true, // Inline runtime logic into the bundle }, };
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:Webpack的模块联邦实现
下一篇:Webpack与Babel的集成