使用 Webpack 导入时出现意外的未定义

Mar*_*nna 3 javascript reactjs webpack

我遇到了一个以前从未发生过的问题:我正在使用 Webpack + Babel 7 编译一个基本的入门浏览器 Web 应用程序(使用 React)。我有三个不同的文件:

  1. withAuth.jsAuth 高阶组件
  2. NavBar.js导航栏组件
  3. Login.js登录表格

如果我在导航栏中导入withAuthHOC 一切正常,但如果我withAuth在 Login.js 文件中导入组件,它会返回undefined

/** withAuth.js */

console.log('withAuth Loaded');

const withAuth = Child => ChildProps => (
    <AuthContext.Consumer>
        { authClient => <Child {...ChildProps} authClient={authClient} }
    </AuthContext.Consumer>
)

export { withAuth };


/** NavBar.js */
import { withAuth } from 'HOC/Auth';

console.log('NavBar Loaded', withAuth); // <- My HOC

const NavBarComponent = (authClient) => { /* ... My Code ... */ }

const NavBar = withAuth(NavBarComponent);

export default NavBar;


/** Login.js */
import { withAuth } from 'HOC/Auth';

console.log('Login Loaded', withAuth); // <- undefined ??

const LoginFormComponent = (authClient) => { /* ... My Code ... */ }

const LoginForm = withAuth(LoginFormComponent);
//                /|\
//                 |
//    Will produce an Error, withAuth is Undefined
Run Code Online (Sandbox Code Playgroud)

这是我的 Webpack 配置:

/** webpack.config.js */

module.exports = {
    entry: { core: 'index.js' },
    resolve: {
        alias: {
            HOC: './path/to/hoc/folder'
        }
    },
    optimization: {
        runtimeChunk: 'single',
        splitChunks: {
            chunks: 'all'
        }
    },
    plugins: [ /* Various Plugin */ ],
    module: {
       rules: [ /* My Rules */ ]
    }
}
Run Code Online (Sandbox Code Playgroud)

有人知道为什么我的 HOC 是这样吗undefined

编辑: 我已将控制台日志放置在树文件中。结果是:

'Login Loaded' - undefined
'withAuth Loaded'
'NavBar Loaded' - function() { }
Run Code Online (Sandbox Code Playgroud)

编辑2: 这是文件结构:

app/
|-high-order-component/
| |-auth/
|   |-withAuth.js
|
|-layout-component/
| |-navbar/
|   |-index.js
|
|-pages/
  |-auth/
    |-login.js
Run Code Online (Sandbox Code Playgroud)

Mar*_*nna 5

解决

经过一下午的大量测试和研究,我找到了问题的解决方案。正如我在问题中所说,我的项目是一个更大的项目,我只写了部分结构,因为我认为问题出在这三个文件中。

实际上,问题是循环依赖问题,而不是 Webpack 配置问题。在我的项目中,我有一个名为“Route”的模块,它存储所有路径和路径的所有组件,因此我可以使用 Array Map 函数构建 React Router。该模块有一个函数,允许我通过路径进行路由,并且可以将路径字符串返回到组件。我的问题是由于该模块经常在项目中被调用,并且这创建了循环依赖关系。

Webpack 在编译过程中不会显示循环依赖,但我发现添加一个名为CircualDependencyPlugin 的插件很有用。当发现循环依赖时,该插件将中断 Webpack 编译。

将模块拆分Route为两个文件解决了我的问题。