JS依赖优先级

时间:2018-03-11 15:56:20

标签: javascript typescript react-native

我在这样的目录中有3个文件:

models
     |_ Service.js
     |_ Agent.js
     |_ index.js

Index.js

export * from Service;
export * from Agent;

Agent.js

class Agent {

  id = 0
}
export {Agent}

Service.js

import {Agent} from '.'

class Service {
   agent = new Agent();
}

export {Service}

但是,当我想创建Service的实例时,Agent类型未定义,而如果我更改index.js中的导出优先级,则问题将得到解决。

index.js(更改优先级后)

export * from Agent;
export * from Service;

有人请告诉我哪里弄错了吗?

1 个答案:

答案 0 :(得分:3)

上面的代码包含循环依赖,这里不需要。

进口应该明确声明一个模块依赖于另一个模块。

应该是:

import {Agent} from './Agent'

class Service {
   agent = new Agent();
}

export {Service}

在这种情况下,在index.js中导入它们的顺序无关紧要。