简体   繁体   English

使用 styled-components 导致 `cannot read withConfig of undefined`

[英]Using styled-components results in `cannot read withConfig of undefined`

When attempting to transpile the Spacing.js file, it results in an undefined import even when styled-components was seemingly being imported and used (in the same way) successfully in other files.当尝试转译Spacing.js文件时,即使styled-components似乎在其他文件中成功导入和使用(以相同方式),也会导致未定义的导入。 Even when removing the styled-components babel plugin, a similar error occurs.即使删除了 styled-components babel 插件,也会发生类似的错误。

.babelrc

{
  "presets": [["es2015", { "modules": false }], "react-native"],
  "plugins": [
    ["styled-components", { "displayName": true }],
    "react-hot-loader/babel",
    "react-native-web",
    "transform-decorators-legacy",
    "transform-class-properties"
  ],
  "env": {
    "production": {
      "plugins": [
        "transform-react-inline-elements",
        "transform-react-constant-elements"
      ]
    }
  }
}

Spacing.js - Code before transpilation Spacing.js - 转译前的代码

import React, { Component, Node } from "React";
import styled from "styled-components";

type Props = {
  size: string,
  color: string,
  fullWidth?: boolean
};

class SpacingComponent extends Component<Props> {
  render(): Node {
    const { size, color, fullWidth = false } = this.props;
    return <Spacing size={size} color={color} fullWidth={fullWidth} />;
  }
}

const Spacing = styled.View`
  height: ${props => props.size}px;
  background-color: ${props => props.color || "transparent"};
  width: ${props => {
    return props.fullwidth ? "100%" : props.size + "px";
  }};
`;

export default SpacingComponent;
  1. Generated code for importing and resolving styled-components用于导入和解析styled-components生成代码

在此处输入图片说明

  1. Generated code for using the styled-components library (v3.2.5)使用styled-components库(v3.2.5)生成的代码

在此处输入图片说明

  1. The resulting error由此产生的错误

在此处输入图片说明

Another example can be seen when removing the styled-components babel plugin from the babelrc, thus the withConfig is not added.另一个例子是从 babelrc 中删除styled-components babel 插件,因此没有添加 withConfig。

  1. Generated error with no styled-components babel plugin没有styled-components babel 插件时生成错误

在此处输入图片说明

  1. Generated code making this error生成的代码导致此错误

在此处输入图片说明


Is babel or webpack adding .default when it doesn't need to, if so, how could I investigate why? babel 或 webpack 是否在不需要时添加.default ,如果是这样,我该如何调查原因?

尝试做styled(View)而不是styled.View

不确定这是否对任何人都有帮助,但对我来说,同样的错误被触发,如style.something并使用 html 元素(例如style.span

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM