webpack 5 module.hot 未定义

webpack 5 module.hot 未定义

问题描述:

我最近将我们的 react 应用程序升级到 webpack5,一切正常,但浏览器错误提示 Uncaught ReferenceError: module is not defined 在此代码上:

I recently upgraded our react app to webpack5 and everything works fine but the browser error saying Uncaught ReferenceError: module is not defined on this code:

if (module.hot) {
    module.hot.accept('./Layout/Layout', () => {
        render();
    });
}

谁能解释一下发生了什么以及我可以做些什么来解决这个问题?

can anyone explain what happened and what I could do to fix this?

在 webpack5 中,所有 nodejs 变量,如 processmodule 都被删除,以便获得 module.hot 在 webpack 5 中你需要使用 import.meta.webpackHot 并将你的代码更改为:

in webpack5 all nodejs variable like process or module is removed so to get module.hot in webpack 5 you need to use import.meta.webpackHot and change your code to this:

    if (import.meta.webpackHot) {
        import.meta.webpackHot.accept('./Layout/Layout', () => {
            render();
        });
    }