设置 babel-plugin-styled-components + Typescript + create-react-app

8
我们目前正在尝试将 `babel-plugin-styled-components` 集成到基于 `typescript` 和 `create-react-app` 的设置中,以获得更好的调试体验,但我们在进行时遇到了困难。
我们不想弹出应用程序,这就是为什么我们正在尝试使用 `react-app-rewired` 进行设置,并且我们还成功使用 `react-app-rewire-typescript` 和 `react-app-rewire-styled-components` 编译了我们的 typescript 代码。 然而,由于某种原因,没有应用 `displayName`,这让我认为 babel 插件没有被应用。 我们使用 `“start”:“react-app-rewired start”` 作为开发服务器脚本,并且 `config-overrides.js` 如下所示:
const rewireTypescript = require('react-app-rewire-typescript');
const rewireStyledComponents = require('react-app-rewire-styled-components');

module.exports = function override(config, env) {
    return rewireTypescript(rewireStyledComponents(config, env), env);
}

我不知道我们错过了什么。交换 rewire... 函数的封装也没有帮助。

这里有没有任何人有相关经验或者可以指点我正确的方向?


我也遇到了同样的问题,你有关于这个问题的任何更新吗? - copia li
Austin Brunkhorst可能已经创造了一个合适的解决方案,因为他也遇到了完全相同的问题。他创建了一个名为babel-plugin-styled-components-typescript的单独版本的Babel插件,似乎与TypeScript兼容。不幸的是,我目前正在一个没有TypeScript的不同项目上,无法验证这个解决方案。你需要自己尝试一下。在这里找到相关讨论: https://spectrum.chat/thread/1cb6a569-f86a-4feb-a950-e4bf0d410050?m=MTUzNDE5ODc4NjgwOA== - manu_unter
2个回答

2
如果你正在使用webpack,我发现了一个解决方案,不需要使用babel。
使用方法是将自定义转换器添加到你的typescript loader中: https://github.com/Igorbek/typescript-plugin-styled-components
module: {
  rules: [
    {
      test: /\.tsx?$/,
      loader: 'awesome-typescript-loader',
      options: {
        getCustomTransformers: () => ({ before: [styledComponentsTransformer] })
      }
    }

这解决了在使用styled-components和typescript时displayName没有显示的问题。

如果我使用Babel 7来转换TS会怎样? - coinhndp
@coinhndp,我们已经将TS转换器迁移到了Babel 7,效果非常好。由于Babel不支持所有的TS语法(请参见此处的“注意事项”部分:https://devblogs.microsoft.com/typescript/typescript-and-babel-7/),因此需要进行一些微调。但是通过切换,我们可以获得babel样式组件插件的所有一流支持,并且现在可以在应用程序以及测试中使用相同的TS编译器(Jest本地依赖于babel)。强烈推荐进行切换。 - Mark Roseboom

1

我通过在config-overrides.js中使用react-app-rewired添加了类似以下内容的解决方案:

const createStyledComponentsTransformer = require('typescript-plugin-styled-components').default;
const styledComponentsTransformer = createStyledComponentsTransformer();

module.exports = function override(config, env) {

const rule = config.module.rules.filter(l => l.oneOf)[0];
const tsLoader = rule.oneOf.filter(l => String(l.test) === String(/\.(ts|tsx)$/))[0];
tsLoader.use[0].options.getCustomTransformers = () => ({
before: [styledComponentsTransformer]
  });

return config;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接