我有一个以前从未遇到过的问题:我正在用Webpack + Babel 7编写一个基本的入门浏览器web应用程序(与React)。我有三个不同的文件:
withAuth.js高阶分量NavBar.js NavBar组件Login.js登录表单如果我在withAuth文件中导入NavBar自定义的withAuth组件,则一切正常,但如果在Login.js文件中导入withAuth组件,则返回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这是我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 */ ]
}
}任何人都知道为什么我的专案是undefined
编辑:我在树文件中放置了控制台日志。结果是:
'Login Loaded' - undefined
'withAuth Loaded'
'NavBar Loaded' - function() { }编辑2: --这是文件结构:
app/
|-high-order-component/
| |-auth/
| |-withAuth.js
|
|-layout-component/
| |-navbar/
| |-index.js
|
|-pages/
|-auth/
|-login.js发布于 2019-06-29 17:40:12
解析
经过整个下午的测试和研究,我终于找到了解决问题的办法。正如我在问题中所说的,我的项目是一个更大的项目,我只写了它的部分结构,因为我认为问题就在这三个文件中。
实际上,这个问题是一个循环依赖问题,而不是Webpack配置问题。在我的项目中,我有一个名为“路由”的模块,它存储路径的所有路径和所有组件,因此我可以使用Array Map函数构建Reactive路由器。该模块有一个函数,允许我通过路径路由,并且可以将路径字符串返回给组件。我的问题是由于这个模块经常在项目中被调用,这就产生了一个循环依赖。
Webpack在编译过程中没有显示循环依赖,但我发现添加一个名为CircualDependencyPlugin的插件很有用。当找到电路依赖时,这个插件会破坏Webpack的编译。
将Route模块分成两个文件解决了我的问题。
https://stackoverflow.com/questions/56818182
复制相似问题