【问题标题】:Using styled-components results in `cannot read withConfig of undefined`使用 styled-components 会导致`cannot read withConfig of undefined`
【发布时间】:2018-09-24 06:13:33
【问题描述】:

尝试转译Spacing.js 文件时,即使styled-components 看似已在其他文件中成功导入和使用(以相同方式),也会导致未定义的导入。即使移除 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 - 转译前的代码

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. 生成的代码用于导入和解析styled-components

  1. 为使用 styled-components 库 (v3.2.5) 生成的代码

  1. 产生的错误

另一个例子可以看到从 babelrc 中删除 styled-components babel 插件,因此没有添加 withConfig。

  1. 在没有styled-components babel 插件的情况下生成错误

  1. 生成的代码导致此错误


babel 或 webpack 是否在不需要时添加 .default,如果是,我该如何调查原因?

【问题讨论】:

  • 不是问题的解决方案,但我建议切换到 env preset 而不是 es2015,原因在链接页面上有所描述
  • 我最初使用的是 env 并切换到 es2015 以查看我的 env 配置是否导致错误,但事实并非如此。感谢您提醒我切换回来

标签: javascript reactjs webpack babeljs styled-components


【解决方案1】:

尝试使用styled(View) 而不是styled.View

【讨论】:

  • 它说 View 不存在,因为它现在是一个变量而不是一个属性......谁赞成这个请帮帮我们,谢谢
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2017-08-17
    • 1970-01-01
    • 2014-12-22
    • 2021-06-25
    • 2020-01-21
    • 2022-12-27
    • 1970-01-01
    • 2021-11-03
    • 2021-11-08
    相关资源
    最近更新 更多