企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## webpack-dev-middleware `webpack-dev-middleware` 是一个容器(wrapper),它可以把 webpack 处理后的文件传递给一个服务器(server)。 `webpack-dev-server` 在内部使用了它,同时,它也可以作为一个单独的包来使用,以便进行更多自定义设置来实现更多的需求。接下来是一个 webpack-dev-middleware 配合 express server 的示例。 安装 ``` yarn add express webpack-dev-middleware -D ``` 新建 `conf/server.js` 输入 ```js const express = require('express'); const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware'); const app = express(); const config = require('./webpack.base.js'); const compiler = webpack(config); // Tell express to use the webpack-dev-middleware and use the webpack.config.js // configuration file as a base. app.use(webpackDevMiddleware(compiler, { publicPath: config.output.publicPath })); // Serve the files on port 3000. app.listen(3000, function () { console.log('Example app listening on port 3000!\n'); }); ``` 修改 `conf/webpack.base.js` ```js const path = require('path'); module.exports = { entry: { main: './src/main.js' }, output: { path: path.resolve(__dirname, '..', 'dist'), filename: '[name].[chunkhash].js', publicPath: '/' } }; ``` 修改 `package.json` ```json "scripts": { "start": "webpack-dev-server --config conf/webpack.base.js", "watch": "webpack --watch --config conf/webpack.base.js", "build": "webpack", "server": "node conf/server.js" }, ``` 这样,就可以输入 `npm run server` 开启 express 服务器监听文件变动,使用 webpack 进行打包。