【问题标题】:Setting up babel-plugin-styled-components + Typescript + create-react-app设置 babel-plugin-styled-components + Typescript + create-react-app
【发布时间】:2018-09-10 02:37:06
【问题描述】:

我们目前正在尝试将babel-plugin-styled-components 集成到基于typescriptcreate-react-app 的设置中,以获得更好的调试体验,但我们在这样做时遇到了困难。

我们不愿意弹出应用程序,这就是我们尝试使用react-app-rewired 设置它的原因,我们还设法让我们的打字稿代码使用react-app-rewire-typescriptreact-app-rewire-styled-components 进行编译。 然而由于某种原因,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... 函数的封装也没有帮助。

这里有没有人有这方面的经验或者可以指出正确的方向?

【问题讨论】:

  • 我也有同样的问题,请问您有针对此问题的更新吗?
  • Austin Brunkhorst 可能已经创建了一个合适的解决方案,因为他遇到了完全相同的问题。他创建了一个单独版本的 babel 插件,名为 babel-plugin-styled-components-typescript,它似乎与 typescript 兼容。不幸的是,我无法验证解决方案,因为我目前正在另一个没有打字稿的项目中。你必须自己尝试一下。在此处找到相关讨论:spectrum.chat/thread/…

标签: reactjs typescript babeljs create-react-app styled-components


【解决方案1】:

如果你使用 webpack,我找到了一个不需要使用 babel 的解决方案。

https://github.com/Igorbek/typescript-plugin-styled-components

要使用它,你可以使用 webpack 向你的 typescript 加载器添加一个自定义转换:

module: {
  rules: [
    {
      test: /\.tsx?$/,
      loader: 'awesome-typescript-loader',
      options: {
        getCustomTransformers: () => ({ before: [styledComponentsTransformer] })
      }
    }

这解决了displayName 在使用样式组件和打字稿时不显示的问题。

【讨论】:

  • 如果我使用 babel 7 改造 TS 会怎样?
  • @coinhndp 我们已经转移到 babel 7 进行 TS 转换,效果很好。由于 Babel 不支持所有 TS 语法,因此需要进行一些细微的调整(请参阅此处的“警告”部分:devblogs.microsoft.com/typescript/typescript-and-babel-7)。但是通过切换,我们获得了 babel 样式组件插件的所有第一类支持,现在可以在我们的应用程序和测试中使用相同的 TS 编译器(Jest 原生依赖于 babel)。会推荐开关。
【解决方案2】:

我通过使用 react-app-rewired 在 config-overrides.js 中添加类似这样的内容解决了这个问题:

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;
}

【讨论】:

    猜你喜欢
    • 2018-06-06
    • 2022-07-29
    • 2020-01-18
    • 2019-10-29
    • 2018-10-14
    • 2019-05-26
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    相关资源
    最近更新 更多