ES6导入/导出语法难度大

时间:2016-03-09 22:51:28

标签: javascript ecmascript-6

我目前有一个目录结构如下,其中+表示一个文件夹:

+ middleware
  - index.js
  + tracking
    - index.js
    + googleAnalytics
      - index.js
      - logPageView.js
      - trackPanos.js
    + mixpanelAnalytics
      - index.js
      - trackUser.js
- index.js

index.jsgoogleAnalytics目录中的最低级别mixPanel文件如下所示:

--/middleware/tracking/googleAnalytics/index.js
import {logPageView} from './logPageView';
import {trackSignup} from './trackSignup';
export const googleAnalyticsMiddleware = [logPageView, trackSignup];

--/middleware/tracking/googleAnalytics/index.js
import {trackPanos} from './trackPanos';
export const mixpanelAnalyticsMiddleware = [trackPanos];

出于某种原因,我可以通过直接查找相关文件路径来成功导入内容。这是ROOT index.js:

--/index.js

import {mixpanelAnalyticsMiddleware} from './middleware/tracking/mixpanelAnalytics';
import {googleAnalyticsMiddleware} from './middleware/tracking/googleAnalytics';

// This works! But notice how deep I have to dig.

理想情况下,我想要这样的东西:

// This does not work!

--/index.js
import * from './middleware';

--/middleware/index.js
export * from './tracking';

--/middleware/tracking/index.js
export * from './mixpanelAnalyticsMiddleware';
export * from './googleAnalyticsMiddleware';

1 个答案:

答案 0 :(得分:1)

您应该使用import * as xxx语法。

所以,当你有

export const googleAnalyticsMiddleware = [logPageView, trackSignup];
export const mixpanelAnalyticsMiddleware = [trackPanos];

在您导入的js文件中,它看起来像

import * as Middleware from './middleware/file/path';
// ...
Middleware.googleAnalyticsMiddleware.doSomething();
Middleware.mixpanelAnalyticsMiddleware.doSomething();