Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up babel-plugin-styled-components + Typescript + create-react-app

We are currently trying to integrate the babel-plugin-styled-components into our typescript and create-react-app based setup for a better debugging experience and we are having difficulties doing so.

We are reluctant to eject the app, which is why we are trying to set it up using react-app-rewired and we also managed to get our typescript code to compile using react-app-rewire-typescript along with react-app-rewire-styled-components. For some reason however, the displayName is not applied, which makes me think the babel plugin is not applied. We are using "start": "react-app-rewired start" as our dev server script and the config-overrides.js looks like this:

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

I have no idea what we are missing. Swapping the encapsulation of the rewire... functions also didn't help.

Does anyone here have experience with that or can point me in the right direction?

like image 548
manu_unter Avatar asked Mar 31 '18 06:03

manu_unter


2 Answers

If you are using webpack, I found a solution that did not require using babel.

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

To use it, you add a custom transform to your typescript loader with webpack:

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

This solves the displayName not showing when using styled-components and typescript.

like image 111
Mark Roseboom Avatar answered Oct 26 '22 14:10

Mark Roseboom


I solved the issue by add something like this in config-overrides.js using 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;
}
like image 40
copia li Avatar answered Oct 26 '22 13:10

copia li