使用webpack-dev-server Node API重新加载热模块

时间:2019-10-30 23:14:22

标签: javascript node.js webpack

我正在努力做到这一点,这样我就可以使webpack分别输出2个捆绑文件(客户端和服务器),同时为两者启用热重载。我为此使用Node.JS直接API,而不是CLI。

我已经阅读了多编译器选项中的一些内容,但是我还不清楚如何使实时重装也能用于我的Express服务器。我的最终目标是自动启动我的Express服务器,并使其热重新加载我对下面该服务器文件所做的任何更改。

服务器

const express = require('express')
const app = express()
const port = 3002

app.get('/', (req, res) => res.send('tests!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Webpack配置文件

  const { client } = webpackConfig()

  const devServer = { host, port, ...client.devServer }

  WebpackDevServer.addDevServerEntrypoints(client, devServer)
  const compiler = webpack(client)

  const server = new WebpackDevServer(compiler, devServer)
  server.listen(port, host, err => {
    if (err) {
      console.error(err)
      process.exit(1)
    } else if (args.open) {
      openBrowser(`http://${host}:${port}${publicPath}/`)
    }
  })

Webpack配置对象(在控制台记录时)

{ entry: './src/server.js',
  output:
   { path: '/project/target/webapp',
     filename: 'bundle.server.js',
     globalObject: 'this' },
  plugins:
   [ DefinePlugin { definitions: [Object] },
     NamedModulesPlugin { options: {} },
     HotModuleReplacementPlugin {
       options: {},
       multiStep: undefined,
       fullBuildTimeout: 200,
       requestTimeout: 10000 },
     HtmlWebpackPlugin {
       options: [Object],
       childCompilerHash: undefined,
       childCompilationOutputName: undefined,
       assetJson: undefined,
       hash: undefined,
       version: 4 },
     ProgressPlugin { profile: undefined, handler: [Function] } ],
  externals: [ [Function] ],
  module: { rules: [ [Object] ] },
  resolve:
   { alias: {},
     extensions: [ '.mjs', '.js', '.json', '.jsx', '.ts', '.tsx' ],
     modules:
      [ 'src/main/webapp/',
        'src/main/webapp/js',
        'src/main/webapp/css',
        'src/main/webapp/lib/',
        'node_modules' ] },
  devServer:
   { watchOptions: { poll: 1000 },
     publicPath: '/dat',
     hotOnly: true,
     inline: true,
     disableHostCheck: true,
     historyApiFallback: true,
     contentBase:
      '/Users/Desktop/proj/src/main/resources',
     proxy:
      { '/admin': [Object],
        '/search': [Object],
        '/services': [Object],
        '/webjars': [Object] } },
  mode: 'development',
  devtool: 'cheap-module-eval-source-map',

我分解为webpack配置的服务器部分如下所示:

const server = () => ({
  target: 'node',

  // Tell webpack the root file of our
  // server application
  entry: './src/main/webapp/server.js',

  // Tell webpack where to put the output file that is generate
  output: {
    path: resolve('./target/webapp'),
    filename: 'bundle.server.js',
    globalObject: 'this',
  },
  externals: [webpackNodeExternals()],
  module: {
    rules: [
      {
        test: /\.js?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        options: {},
      },
    ],
  },
})

0 个答案:

没有答案