怎么在webpack中利用express实现自动刷新?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
配置webpack
首先就是配置webpack的配置。新建一个webpack.config.js文件
const path = require('path') const webpack = require('webpack') var hotMiddlewareScript = 'webpack-hot-middleware/client' module.exports = { entry: { main: ['./src/main.js', hotMiddlewareScript] }, mode: 'development', output: { path: path.resolve(__dirname, 'public'), filename: 'js/[name].js', publicPath: '/' }, resolve: { extensions: ['.js'] }, plugins: [ new webpack.optimize.OccurrenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin() ] }
我们这里需要关注的是,每个entry后都要增加一个hotMiddlewareScript,还有就是增加3个插件
首先新建一个webpack.middleware文件,这里我们需要用到webpack-dev-middleware和 webpack-hot-middleware两个中间件。
const webpack = require('webpack') const webpackDevMiddleware = require('webpack-dev-middleware') const webpackHotMiddleware = require('webpack-hot-middleware') const webpackConfig = require('./webpack.config') module.exports = app => { let compiler = webpack(webpackConfig) app.use(webpackDevMiddleware(compiler, { publicPath: '/', stats: { colors: true, chunks: false } })) app.use(webpackHotMiddleware(compiler)) }
注意:webpack-dev-middleware和webpack-hot-middleware的静态资源服务仅仅用于开发环境。到了生产环境,应该使用express.static()。
下面编写express代码
const express = require('express') const bodyParser = require('body-parser') const {resolve} = require('path') const webpackMiddleware=require('./webpack.middleware') const router = express.Router() const app=express() const port = process.env.PORT || 3000 webpackMiddleware(app) app.use(express.static(resolve(__dirname,'./public'))) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: true })) // ...代码 app.use(router) app.listen(port, () => { console.log(`Server listening on http://localhost:${port}, Ctrl+C to stop`) })
关于怎么在webpack中利用express实现自动刷新问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。