4

I have a web project with a working Webpack4 config using webpack-dev-server with HMR enabled and started this way via npm script:

cross-env NODE_ENV=development webpack-dev-server --inline --hot

All is OK, HMR works for my js and scss files. Now I'm wondering if it's possible to extend my Webpack config to have a full reload in the browser when I modify a view template file.

It seems for me that webpack-dev-server can't do this on its own, so I think I need some other plugin. After googling a bit this is I've got:

  1. webpack-dev-server + browser-sync-webpack-plugin
  2. rewrite my config to webpack-serve as it seems it can do it
  3. chokidar + webpack-dev-middleware (API for reloading?)

So my question is what is the best way to get HMR + watch given paths and reload browser on file change (blade/twig/php/etc...) with Webpack 4(.17.2) ?

Relevant part of my current config:

devServer: {
  index: '',
  open: true,
  hotOnly: true,
  publicPath: '/build/',
  host: 'mysite.test',
  proxy: {
    '**': {
      target: 'http://mysite.test',
      changeOrigin: true,
      headers: {
        'X-Dev-Server-Proxy': 'http://mysite.test'
      }
    }
  }
}
4

1 回答 1

10

回答我自己,也许其他人可以从中受益。请注意:我有一个 Laravel 项目,我使用 Webpack4 来捆绑它,而不是它自己的 Laravel Mix 解决方案。我的 Laravel 测试站点由 mysite.test 上的 nginx 提供服务

1) webpack-dev-server + BrowserSync

很好用,BrowserSync有很多不错的功能,我喜欢!唯一的缺点是它在 Webpack 的 devserver 之上创建了另一个代理。您可以按照以下步骤尝试:

按照说明安装browser-sync-webpack-plugin,然后:

const BrowserSyncPlugin = require('browser-sync-webpack-plugin');

// Webpack config, plugins section
plugins: [
  new BrowserSyncPlugin({
    host: "mysite.test",
    port: 3000,
    proxy: "mysite.test:8080",
    open: "external",
    files: [
      './resources/views/**/*.blade.php'
    ]
  },{
    // prevent BrowserSync from reloading the page
    // and let Webpack Dev Server take care of this
    reload: false
  })
]

2) webpack-服务

由于webpack-contrib/webpack-serve已被弃用,因此不再可选。

3) webpack-dev-server + Chokidar

最后我开始使用这个。简单快速。Chokidar是一个文件观察器,它也被 Webpack 的开发服务器在内部用于观察文件。您可能已经拥有它,node_modules但如果没有,请使用npmor安装它yarn

这是我最初想要的整个 devServer 配置。HMR 处理 CSS 注入和 Javascript 更改,当视图文件更改时,devserver 使浏览器自动重新加载:

const chokidar = require('chokidar');

// Webpack's devServer config
devServer: {
  before(app, server) {
    chokidar.watch([
      './resources/views/**/*.blade.php'
    ]).on('all', function() {
      server.sockWrite(server.sockets, 'content-changed');
    })
  },
  index: '',
  open: true,
  host: 'mysite.test',
  proxy: {
    '**': {
      target: 'http://mysite.test',
      changeOrigin: true,
      headers: {
        'X-Dev-Server-Proxy': 'http://mysite.test'
      }
    }
  }
}

在 Webpack 4.19.1 上测试

于 2018-09-24T09:22:26.637 回答