How do you set the namespace for styled components when using create-react-app?

1k views Asked by At

I'm creating a react app with create-react-app. I want to avoid having to eject the webpack config, but I want more control over how my classes are generated.

I'm currently using react-app-rewired and react-app-rewire-styled-components to try and customize the way my styled-component classes are compiled.

According to the documentation this should be possible by setting the namespace

This is my config-overrides.js:

const rewireStyledComponents = require('react-app-rewire-styled-components');

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

    config = rewireStyledComponents(config, env, {
        "displayName": false,
        "namespace": "my-app"
    });

    return config;
}

Now with this config I would expect my class that was previously generated as hfil7l-0 lmhJTL to now be generated as my-app-hfil7l-0 lmhJTL. However, this does not seem to work.

I want to use namespace specifically because displayName and fileName give me too little control. I'm loading several apps on the same page and some share components that are extended styled-components, so I have to make sure I can make all the classes for each app are unique.

What am I missing here?

1

There are 1 answers

0
phamthainb On

You can try with customize-cra for extend some config from CRA.

// config-overrides.js

const { alias, configPaths } = require('react-app-rewire-alias');
const { override, addBabelPlugin } = require('customize-cra');

module.exports = override((config, env) => {
  let isDev = env === 'development';

  // some my alias
  alias({
    ...configPaths('tsconfig.base.json'),
  })(config);

  // It work only dev
  if (isDev) {
    addBabelPlugin([
      'babel-plugin-styled-components',
      {
        displayName: true,
      },
    ])(config);
  }

  return config;
});