3

在将 webpack-dev-middle 与 express 服务器一起使用时,我想使用 webpack-hot-middleware 对提取的 css 文件进行工作(热重载)。

它适用于 webpack-dev-server。但我想将它与快递一起使用。

服务器.js

const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');

const app = express();
const config = require('./webpack.config.js');
const compiler = webpack(config);

app.set('view engine', 'pug')

// 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
}));
// HMR
app.use(require("webpack-hot-middleware")(compiler, {
  log: console.log,
  path: '/__webpack_hmr',
  heartbeat: 10 * 1000
}));
// Render/serve HTML
app.get('/', (req, res) => {
  res.render('layout')
})

// Serve the files on port 3000.
app.listen(3000, function() {
  console.log('Example app listening on port 3000!\n');
});

webpack.config.js

const path = require('path')
const webpack = require('webpack')
const webpackHotMiddleware = require('webpack-hot-middleware')
const hotMidConf = 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000'

module.exports = {
  mode: 'development',
  entry: {
    bundle: [hotMidConf, './src/index.js'],
    style: [hotMidConf, './src/style.scss']
  }, 
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/'
  },
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.js$/,
        use: 'babel-loader'
      },
      {
        test: /\.scss$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'style.css'
            }
          },
          {
            loader: 'extract-loader',
            options: {
              publicPath: './'
            }
          },
          {loader: 'css-loader'},
          {
            loader: 'sass-loader',
            options: {
              includePaths: [path.resolve(__dirname, 'node_modules')]
            } 
          }
        ]
      },
    ]
  },
  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin()
  ]
}

其他一切正常,当我构建时,我从 scss 获取 css 文件。我相信style-loader当它没有被提取但当我尝试它时似乎没有做任何事情时,这就是它的工作原理。

我使用 extract-text-webpack-plugin 找到了很多答案,但据我所知,这不适用于 webpack 4...所以我将 extract-loader 与 file-loader 一起使用。

4

0 回答 0