如何让webpack热重载检测到pug和express的更改?

8

我有一个使用pug和stylus的Express应用程序。我已经配置好了HMR中间件,当我更改stylus时,它会重新加载,但不适用于pug文件的更改。

我想知道我是否缺少特定的配置。我也尝试添加了pug-html-loader,但也没有起作用。

// server.js
app.set('views', path.join(__dirname, 'views')); 
app.set('view engine', 'pug');

const webpackDevMiddleware = require('./hmr').dev;
const webpackHotMiddleware = require('./hmr').hot;
app.use(webpackDevMiddleware);
app.use(webpackHotMiddleware);

// hmr.js
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

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

exports.dev = webpackDevMiddleware(compiler, {
  noInfo: true,
  filename: webpackConfig.output.filename,
  publicPath: webpackConfig.output.publicPath,
  stats: {
    colors: true
  }
});

exports.hot = webpackHotMiddleware(compiler, {
  log: console.log,
  path: '/__webpack_hmr', 
  heartbeat: 10000
});

// webpack.config.js
const javascriptRule = {
  test: /\.js$/,
  use: [
    {
      loader: 'babel-loader',
      options: {
        presets: ['env']
      }
    }
  ]
};

const stylesRule = {
  test: /\.styl$/,
  use: ['style-loader', 'css-loader', 'stylus-loader']
};

module.exports = {
  context: path.join(__dirname, 'javascripts'),
  entry: [
    'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000',
    './index.js'
  ],
  devtool: 'source-map',
  output: {
    path: path.join(__dirname, 'public', 'dist'),
    filename: 'bundle.js',
    publicPath: '/dist/',
    library: 'aux'
  },

  module: {
    rules: [javascriptRule, stylesRule]
  },

  plugins: [new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin()]
}

Pug将在webpack中转换为Javascript,因此它不能像style-loader一样自动加载自己,但具有内置的HMR更新支持。要使您的Pug文件与HMR兼容,您需要使用if(module.hot){module.hot.accept(等。React是另一个具有内置HMR支持的插件,因为Pug只是一个模板引擎而不是Class/Object组件,您将不得不自己处理HMR。请参阅此处有关手动处理HMR的示例-> https://webpack.js.org/guides/hot-module-replacement/ - Keith
1个回答

1

你需要安装raw-loader:https://webpack.js.org/loaders/raw-loader/

Webpack 3配置:

module: {
    rules: [
      {
        test: /\.pug$/,
        use: [
          {loader: 'raw-loader'},
          {loader: 'pug-html-loader'}
        ]
      }
    ]
  },
  plugins: [
    // Templates HTML
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: './src/templates/index.pug'
    }),
    new HtmlWebpackPlugin({
      filename: 'contact.html',
      template: './src/templates/contact.pug'
    }),
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ]

app.js

// import all template pug

import 'raw-loader!./templates/index.pug'
import 'raw-loader!./templates/contact.pug'
...

那会让webpack监听pug文件的变化,但也会将这段js代码添加到bundle.js中,因此您需要处理app.js以清理bundle.js。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接