javascript - Webpack HMR 不适用于 Node-Webkit/NW.js

标签 javascript webpack node-webkit webpack-hmr hot-module-replacement

我有什么

我使用以下配置文件创建了一个小型 Webpack HMR Hello World:

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: {
    app: path.join(__dirname, 'app/index.js'),
  },
  output: {
    path: path.join(__dirname, 'build'),
    filename: 'app.js',
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: [
          'babel-loader',
        ],
        exclude: /node_modules/
      },
    ],
  },
  plugins: [
    new webpack.NamedModulesPlugin(),
  ],
};

然后,我从 npm 脚本运行 webpack-dev-server 并在 http://localhost:8080/app.js 下提供该文件。我将此文件包含在我的 index.html 中,并且所有内容(包括 HMR)在浏览器中工作正常。

问题

我安装了 NW.js (Node-Webkit) via npm并将此 index.html 设置为 package.jsonmain 属性的入口点。该应用程序工作正常,但当我编辑文件时,HMR 不会发生。为什么它在浏览器中工作时在 NW.js 中不起作用?

最佳答案

tl;博士

target: 'node-webkit', 添加到您的 webpack.config.js

详细信息(幕后)

作为Webpack 1Webpack 2文档显示,您必须设置一个 target 配置选项,因为不同的环境工作方式不同。例如,对于 node-webkit 选项,文档指出:

Compile for usage in webkit, uses jsonp chunk loading but also supports build in node.js modules plus require(“nw.gui”) (experimental)

此外,对于 node 它指出:

In the example above, using node webpack will compile for usage in a Node.js-like environment (uses Node.js require to load chunks and not touch any built in modules like fs or path).

多个目标

请记住,由于这些差异,在将 node-webkit 设置为目标后,网络版本将无法在您的浏览器中运行。如果您想在这两种环境中进行开发,则必须通过引入具有自己的输出的多个配置来创建同构库。到底如何Webpack 2 Multiple Targets documentation是吗:

var path = require('path');
var serverConfig = {
  target: 'node',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'lib.node.js'
  }
  //…
};

var clientConfig = {
  target: 'web', // <=== can be omitted as default is 'web'
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'lib.js'
  }
  //…
};

module.exports = [ serverConfig, clientConfig ];

关于javascript - Webpack HMR 不适用于 Node-Webkit/NW.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42446067/

相关文章:

javascript - 如何在表格中查找值,然后抓取相邻单元格中的数据

javascript - prependTo 后现有 div 上的 jQuery 幻灯片动画

javascript - 导入文件而不在末尾添加 .jsx 不起作用

javascript - CSS 不适用于 Webpacked 模块

javascript - HTML 选择选项显示 future 12 个月

javascript - groupBy 与 Lodash 模块

javascript - Node.js错误: "Unexpected token ;" while on node-webkit

windows - Node-webkit 本地网络服务器

javascript - 用 webpack 填充一个包

javascript - 在 Node-webkit 中将 Canvas 保存到磁盘