【问题标题】:named import throws errors whereas import * from doesn't命名导入会引发错误,而 import * from 不会
【发布时间】:2019-07-03 05:56:03
【问题描述】:

考虑一下我的 react 应用中功能的以下文件夹结构:

feature1
    actions
        actionTypes.js
        crud.js
    component.js
    container.js
    reducer.js
    sagas.js
    sagas.test.js
    services.js
    index.js


feature2
    actions
        actionTypes.js
        crud.js
    component.js
    container.js
    reducer.js
    sagas.js
    sagas.test.js
    services.js
    index.js

index.js 文件中,我正在导入各个功能的组件、容器、reducer 等,并从索引文件中导出相同的内容。

例如:feature1/index.js

import myReducer from './reducer';
import * as mySagas from './sagas';
import * as myServices from './services';
import * as myCRUD from './actions/crud';
import Component from './component';
import Container from './container';
import * as actionTypes from './actions/actionTypes';

export {
  myReducer,
  actionTypes,
  myCRUD,
  mySagas,
  myServices,
  Component,
  Container,
};

现在在feature2sagas.test.js文件中,我可以导入feature1的服务如下:

import { myServices } from '../feature1';

当我运行我的 Jest 测试时,上面的行导致失败:TypeError: window.locale_name is not a functionwindow.locale_name 是在 feature1 中导入的第三方库中定义的函数。但另一方面,如果我按以下方式导入相同的内容,则不会引发错误。

import * as myServices from '../feature1/services';

【问题讨论】:

  • feature1 有命名导出吗?还是默认导出?

标签: javascript reactjs import jestjs


【解决方案1】:

在我看来,导入的 myServices 取决于设置的 window.locale_name。导入* 的原因可能是因为在feature1/index.js 的导出值中,其中一个在myServices 之前导出的值设置了您的myServices 将使用的window.locale_name

我相信使用 ES6 模块,只有运行您导入的导出代码才能进行树抖动。

【讨论】:

  • 感谢您的回答,但不幸的是不是这样。我尝试将myServices 导出为 index.js 文件中的最后一项,但无济于事。
  • @cbalawat 将 myServices 放在导出中的哪个位置并不重要;如果您使用解构导入,则不会加载其依赖项,并且您的脚本将失败。尝试将 myServices 作为文件中的第一项导出,并使用 '* as' 导入,您应该会看到它失败,原因与未加载它的依赖项相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
  • 2023-02-13
  • 1970-01-01
  • 2021-05-20
相关资源
最近更新 更多