【问题标题】:create-react-app, code splitting and jestcreate-react-app,代码拆分和玩笑
【发布时间】:2017-06-13 09:21:42
【问题描述】:

我正在使用 create-react-app 开发一个应用程序,并且我正在尝试将我的代码拆分为实现 react-router huge-apps 示例中描述的方式的模块。 除了单元测试之外,一切都运行良好:我在运行路由组件的开玩笑测试时遇到此错误:

TypeError: Cannot read property 'contextTypes' of undefined

路由组件如下所示:

export class IntroPage extends React.Component {
    render() {
        return (
            <div></div>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        ...
    }
};

module.exports = connect(mapStateToProps)(IntroPage);

还有一个测试:

import React from 'react';
import {shallow} from 'enzyme';
import {IntroPage} from '../IntroPage';

it('should render without crashing', () => {
    shallow(
        <IntroPage {...props}/> // IntroPage is undefined
    )
});

我必须如何导出/导入我的组件才能正确测试它们。

谢谢。

【问题讨论】:

  • 为什么在一个文件中同时使用 ES6 导出语法和 CommonJS module.exports?这不受支持。
  • CommonJS 语法支持兼容性,但你不应该在任何新代码中使用它。将它们混合在语义上是错误的,因为它们具有相互冲突的含义。
  • 我知道,但是如果我像在 es6 中那样导出组件(导出默认值),它就不起作用了。
  • 我不得不说我的路由定义是这样的:export default { childRoutes: [ { path: '/', component: require('./components/app/App') }, { path : '*', onEnter: (nextState, replace) => replace('/') } ] };
  • 这是 react-router 示例中暴露的方式。

标签: reactjs webpack react-router react-redux


【解决方案1】:

如果你在 Babel 中编译:

export class IntroPage extends React.Component {
   ...
}

您会注意到 Babel 会将其移动到 exports 变量中。

Object.defineProperty(exports, "__esModule", {
    value: true
});
... more good stuff
...
var IntroPage = exports.IntroPage = function (_React$Component) {

所以你可以 console.log 这些:

console.log(exports);
console.log(module.exports);
console.log(module);

并检查exports 变量和module 对象。 这里module.exports应该和exports一样。

如果你输入:

 module.exports = connect(mapStateToProps)(IntroPage);

在组件文件的末尾,您将用新值覆盖 module.exports

这是问题的核心。

解决办法?

我想你已经找到了,但最好不要将 commonJS 与 ES6 导出混合,因为 ES6 导出将被转换为 commonJS 语法。


还要检查“What is export default in JavaScript?

【讨论】:

  • 谢谢。我知道混合语法不是一个好主意,但由于它是在 react-router 示例中完成的方式,我认为这是一个好主意。 > 但最好不要将 commonJS 与 ES6 导出混合在一起你是什么意思?我仍在将语法与我找到的解决方案混合在一起?我以为我没有。
  • 顺便说一句,react-router 不是一个优秀的产品。当您将它包含在页面上时,它很重,并且您在 Facebook 的默认 React 项目文档中找不到它,如果您搜索 react router alternative,您会发现更多将来不使用它的理由。
  • 当然,但我正在一步一步地前进:)
【解决方案2】:

通过这篇文章找到了解决方案:React router dynamic routes not rendering component

在使用 es6 模块导出时,我只需要在 require 语句中添加“默认”即可。

【讨论】:

    猜你喜欢
    • 2019-05-31
    • 2018-08-04
    • 2020-02-03
    • 2019-08-04
    • 2018-07-27
    • 2019-05-07
    • 2019-02-01
    • 2018-08-31
    • 2020-11-11
    相关资源
    最近更新 更多