我有一个 React 应用程序,它在顶层使用外部共享目录 shared-js,它位于我的应用程序的 src 目录之外。我想为这个共享模块启用热模块替换 (HMR),这样我就可以实时查看它的更改,而不必重新加载整个应用程序(例如,如果我更改该目录中文件中的 console.log) .
我已经尝试将 webpack.HotModuleReplacementPlugin() 添加到我的 webpack.config.js 文件中,并将以下代码添加到我的 shared-js 模块中的 index.js 文件中:
if (module.hot) { module.hot.accept();}
但是,HMR 仍然不适用于对 shared-js 模块所做的更改。
如何在我的 React 应用程序中为 shared-js 模块启用 HMR?
我尝试过的:
将 webpack.HotModuleReplacementPlugin() 添加到 webpack.config.js 添加 if (module.hot) { module.hot.accept(); } 到 shared-js 中的 index.js
代码:
这是我当前的 webpack.config.js 文件:
const paths = require("./paths");
module.exports = {
entry: {
main: paths.appIndexJs,
shared: "../libs/shared-js/index.js",
},
output: {
path: paths.appBuild,
filename: "[name].bundle.js",
},
module: {
rules: [
// ...
],
},
plugins: [
// ...
new webpack.HotModuleReplacementPlugin(),
],
// ...
};
这是我在 shared-js 中的 index.js 文件:
'use strict';
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./types"), exports);
__exportStar(require("./core"), exports);
__exportStar(require("./testing"), exports);
if (module.hot) {
module.hot.accept();
}