多页面应用启用webpack热更新修改文件后会刷新整个页面而不是热替换怎么解决

发布于 2022-09-06 05:07:20 字数 4846 浏览 18 评论 0

./build/webpack.dev.conf.js

const path = require('path')
const config = require('../config')
const baseWebpackConfig = require('./webpack.base.conf')

const webpack = require('webpack')
const merge = require('webpack-merge')

Object.keys(baseWebpackConfig.entry).forEach(function (name) {
  baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})

let webpackConfig = merge(baseWebpackConfig, {
  devtool: '#cheap-module-eval-source-map',
  module: {
    rules: [
      {
        test: /\.styl$/,
        use: ['style-loader', 'css-loader', { loader: 'postcss-loader', options: { sourceMap: 'false' } }, 'stylus-loader']
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': config.dev.env
    }),
    new webpack.HotModuleReplacementPlugin()
  ]
})

./build/webpack.base.conf.js

const path = require('path')
const config = require('../config')
const Util = require('./utils.js')
const HtmlWebpackPlugin = require('html-webpack-plugin')


const webpack = require('webpack')

function resolve(dir) {
  return path.resolve(__dirname, '..', dir)
}

// 获取js的入口文件
let jsFiles = Util.getAllFiles(resolve('src/pages'), 'js', true) // true 表示递归查找
jsFiles = jsFiles.filter((item) => {
  return /(\w+)\/js\/\1\.js$/.test(item)
})
let entry = Util.getEntry(jsFiles, (filename) => {
    return /\/(\w+)\.js$/.exec(filename).pop()
})


// 获取html的模板文件
let htmlFiles = Util.getAllFiles(resolve('src/pages'), 'html', true)
let htmlEntry = Util.getEntry(htmlFiles, (filename) => {
  return /\/(\w+)\.html$/.exec(filename).pop()
})
let htmlPlugins = []
for (let key in htmlEntry) {
  let options = {
    filename: key + '.html',
    template: htmlEntry[key],
    inject: true
  }
  if (entry.hasOwnProperty(key)) {
    options['chunks'] = [key]
  } else {
    options['chunks'] = []
  }
  htmlPlugins.push(new HtmlWebpackPlugin(options))
}



module.exports = {
  entry,
  output: {
    path: config.build.assetsRoot,
    filename: 'js/[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    alias: {
      'lib': resolve('src/lib'),
      'plugins': resolve('src/lib/plugins'),
      'stylus': resolve('src/lib/stylus')
    }
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: ['babel-loader']
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: [{
          loader: 'url-loader',
          options: {
            limit: 8192,
            name: 'images/[name].[ext]' 
          }
        }]
      },
      {
        test: /\.html$/,
        use: ['html-loader']
      },
      {
        test: /\.pug$/,
        use: ['pug-loader?pretty=true']
      }
    ]
  },
  plugins: [
    ...htmlPlugins
  ]
}

./build/dev-server.js

let config = require('../config')


if (!process.env.NODE_ENV) {
  process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
}

const path = require('path')
const opn = require('opn')
const express = require('express')
const webpack = require('webpack')

let webpackConfig = require('./webpack.dev.conf.js')
// default port where dev server listens for incoming traffic
let port = process.env.PORT || config.dev.port
// automatically open browser, if not set will be false
let autoOpenBrowser = !!config.dev.autoOpenBrowser

let app = express()

let compiler = webpack(webpackConfig)

let devMiddleware = require('webpack-dev-middleware')(compiler, {
  publicPath: webpackConfig.output.publicPath,
  quiet: true
})

let hotMiddleware = require('webpack-hot-middleware')(compiler, {
  log: () => {
  }
})

compiler.plugin('compilation', function (compilation) {
  compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
    hotMiddleware.publish({ action: 'reload' })
    cb()
  })
})


// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())

// serve webpack bundle output
app.use(devMiddleware)

// enable hot-reload and state-preserving
// compilation error display
app.use(hotMiddleware)

app.use(config.dev.assetsPublicPath, express.static('./'))

let uri = 'http://localhost:' + port

let _resolve
let readyPromise = new Promise(resolve => {
  _resolve = resolve
})

console.log('> Starting dev server...')
devMiddleware.waitUntilValid(() => {
  console.log('> Listening at ' + uri + '\n')
  // when env is testing, don't need open it
  if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
    opn(uri)
  }
  _resolve()
})

let server = app.listen(port)

module.exports = {
  ready: readyPromise,
  close: () => {
    server.close()
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

弱骨蛰伏 2022-09-13 05:07:20

终于找到原因了,这些配置文件我是照着vue的项目生成文件写的,删掉compiler.plugin('compilation', function (compilation) {这一块就可以。不过这样的话更新html文件就不能自动刷新了。也不能热更新js文件,会提示你module.hot,所以需要在每个入口文件加上这么一段:

if (module.hot) {
  module.hot.accept()
}

不过感觉这样好麻烦,应该可以先判断下NODE_ENV,然后自动为每个入口文件加上这么一段,具体做法还不清楚。。。。先这样

执手闯天涯 2022-09-13 05:07:20

热替换还需要其他的东西支持,如果是用vue的话vue-loader,react需要react-hot-loader

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文