了解ES6中的循环依赖关系
问题描述:
我正在尝试创建一种API。出于这个原因,我尝试导入导入调用来自的文件的主文件(该文件公开了API),其中包括导出文件的情况!了解ES6中的循环依赖关系
令人困惑?大!
项目结构:
/
/src
/src/js
/src/js/modules
/src/js/modules/moduleA/index|actions|components|selectors
/src/js/modules/moduleB/index|actions|components|selectors
/src/js/modules/moduleC/index|actions|components|selectors
见下面,我公开一个循环依赖不起作用的例子!
所以,这里是一个模块化如何公开API(模块本身以外的出口时所能完成的工作):
// src/modules/foobar/index.js
import * as actions from './actions'
import * as components from './components'
import * as containers from './containers'
import * as constants from './constants'
import reducer from './reducer'
import * as selectors from './selectors'
export default { actions, components, containers, constants, reducer, selectors }
这里的进口:
// src/modules/foobar/containers/index.js
import API from '../index.js'
// this is undefined
console.log('API', API)
的目标是什么?
ModuleAPI.actions.foobar()
ModuleAPI.containers.foobar()
虽然我可以看到,它可能是一个坏的做法(但说实话,似乎常理,一个文件无法导入本身)我想明白为什么这是不可能的!
答
这是完全可以导入这样的顶层模块。在容器模块的初始化期间,不可能同步使用它。会发生什么事那么只要您将console.log(API)
的功能,过一会儿给它基本上是
load foobar/index.js
initialise foobar/index.js:
load foobar/containers/index.js
initialise foobar/containers/index.js:
load foobar/index.js
it's already getting initialised so don't wait
set up scope
execute module code: `API` is still undefined in the log statement
finish initialisation of foobar/containers/index.js
set up scope
execute module code: `API` is getting defined now
finish initialisation of foobar/index.js
,它会工作。请注意,对于循环依赖关系,您需要格外小心,即始终首先加载顶级模块以获得一致的评估顺序。
你用什么模块加载器?很确定ES6规范允许循环依赖没有问题。 – CodingIntrigue
Webpack最新@CodingIntrigue – punkbit
您是否在真实浏览器中尝试过您的示例? Chrome,Firefox,Safari TP和Edge都支持本地模块(其中一些支持标志)。 – nils