Webpack热模块无法刷新浏览器

时间:2018-09-10 14:26:02

标签: webpack webpack-dev-middleware webpack-hot-middleware

您好,我想将Webpack与Express和Webpack-dev-middleware一起使用以及热模块更换。我在下面收到消息,但是无论如何浏览器都不会刷新。

我已经坚持了好几天,所以如果有人可以帮助我,那就太好了。我正在提供服务器和Webpack配置文件。预先非常感谢。

[HMR]已连接

app.bundle-26838b.js:1 [HMR]捆绑包在61968ms内重建

我得到了,但是浏览器没有刷新。

server.js

const config = require('./config');

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

const opn = require('opn');
const path = require('path')
const express = require('express');
const https = require('https');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const proxyMiddleware = require('http-proxy-middleware');
const portfinder = require('portfinder')
const fs = require('fs');
const options = {
  key: fs.readFileSync('./certificates/private.key'),
  cert: fs.readFileSync('./certificates/certificate.crt')
};
const webpackConfig = require('./webpack.config')

const port = process.env.PORT || 4000;
const app = express();
const compiler = webpack(webpackConfig);

const devMiddleware = webpackDevMiddleware(compiler, {});

const hotMiddleware = require('webpack-hot-middleware')(compiler);

app.use(hotMiddleware)

// Set up the proxy.
Object.keys(config.dev.proxyTable).forEach(function (context) {
  app.use(proxyMiddleware(context, config.dev.proxyTable[context]));
});

app.use(require('connect-history-api-fallback')())


app.use(devMiddleware);

const uriBase = 'mydomain.local:';

var _resolve, _reject;

const readyPromise = new Promise((resolve, reject) => {
  _resolve = resolve
  _reject = reject
})

var server;
portfinder.basePort = port;

console.log('> Starting dev server...')
const httpsPort = 4000;

const httpsServer = https.createServer(options, app).listen(httpsPort);

devMiddleware.waitUntilValid(() => {

  portfinder.getPort((err, port) => {
    if (err) {
      _reject(err)
    }
    process.env.PORT = port
    const uri = 'https://' + uriBase + port;

    console.log('> Listening at ' + uri + '\n');

    server = app.listen(port, function () {
      console.log('Development server listening on port ' + port);
    });

    _resolve()
  })
})


const staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)

app.use(staticPath, express.static('./dist'))

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

webpack.config.js

const webpack = require('webpack');
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const config = {
  resolve: {
    alias: { 'chart': require.resolve('chart.js') }
  },
  entry: {
    'angular': path.resolve(__dirname, './node_modules/angular/angular'),
    'app': [
      'webpack-hot-middleware/client?path=https://localhost:4000/__webpack_hmr&reload=true',
      './src/app/app.js',
    ],
    'vendor': [
      'webpack-hot-middleware/client?path=https://localhost:4000/__webpack_hmr',
      "lodash",
      "jquery",
      "jquery-ui",
      "angular",
      "@uirouter/angularjs",
      "angular-aria",
      "angular-material",
      "angular-route",
      "angular-sanitize",
      "angular-scroll",
      "angular-ui-bootstrap",
      "angular-ui-sortable",
      "bootstrap",
      "fullcalendar",
      "html2canvas",
      "moment",
      "moment-range",
      "moment-timezone",
    ]
  },
  output: {
    filename: 'libs/[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: ['ng-annotate-loader', 'babel-loader']
      },
      {
        test: /\.less$/,
        use: ExtractTextWebpackPlugin.extract({
          use: ['css-loader', 'less-loader'],
        })
      },
      {
        test: /\.css$/,
        use: [
          { loader: "style-loader" },
          { loader: "css-loader" }
        ]
      },
      {
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
        loader: 'url-loader?limit=10000',
        options: {
          name: './fonts/**/[name].[ext]'
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf|svg|png)$/,
        loader: 'file-loader',
      },
      {
        test: /\.html$/,
        exclude: path.resolve(__dirname, './src/app/app.html'),
        use: [
          'ngtemplate-loader?relativeTo=' + (path.resolve(__dirname, './src/app')),
          {
            loader: 'html-loader',
            options: {
              attrs: [
                'img:src',
                ':template-url',
              ],
            },
          },
        ],
      },
    ],

  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      comments: false,
      sourceMap: false,
    }),
    // new CleanWebpackPlugin('dist'),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      names: ['app', 'vendor'],
      filename: 'libs/[name].bundle-[hash:6].js'
    }),
    new HtmlWebpackPlugin({
      template: './src/app/app.html'
    }),
    new CopyWebpackPlugin([
      { from: 'src/app/styles/img', to: 'styles/img' },
      { from: 'src/app/styles/fonts', to: 'styles/fonts' },
      { from: 'releases/templates/development', to: './' }
    ]),
    new webpack.ProvidePlugin({
      jQuery: 'jquery',
      $: 'jquery',
      jquery: 'jquery',
      _: 'lodash',
      moment: 'moment',
    }),
    new ExtractTextWebpackPlugin('styles/styles.css'),
    new OptimizeCssAssetsWebpackPlugin(),
  ],
  watchOptions: {
    ignored: /node_modules/,
  },
};

module.exports = config;

1 个答案:

答案 0 :(得分:0)

我实际上是通过更改此行来解决的

  'webpack-hot-middleware/client?path=https://localhost:4000/__webpack_hmr&reload=true',

  'webpack-hot-middleware/client?path=//localhost:4000/__webpack_hmr&reload=true',

我希望它对以后的人有所帮助。