How can I use Astroturf with Create React App?

1k Views Asked by At

I tried using its babel plugin, but that didn't work.

I am also using craco to extend/customize Create React App, but I don't know enough Webpack to make craco work with Astroturf.

2

There are 2 best solutions below

0
On BEST ANSWER

To make astroturf working you should push one new rule to generated by Create React App webpack rules:

{
    test: /\.(js|mjs|jsx|ts|tsx)$/,
    use: [
        {
            loader: 'astroturf/loader',
            options: { extension: '.module.scss' },
        },
    ],
}

With react-app-rewired, config-overrides.js will look like:

module.exports = (config) => {
    config.module.rules.push({
        test: /\.(js|mjs|jsx|ts|tsx)$/,
        use: [
            {
                loader: 'astroturf/loader',
                options: { extension: '.module.scss' },
            },
        ],
    });
    return config;
};

With craco it should be similar

Note: .module.scss should be replaced with .module.css in case of plain css

0
On

I found that Anton's answer didn't work for my project - the astroturf loader overwrote the built-in loader from CRA. I've had success with this config-overrides.js:

const { override, getBabelLoader, addWebpackModuleRule } = require("customize-cra");

const addAstroturf = plugin => config => {
  const babel = getBabelLoader(config);
  babel.loader = [
    { loader: babel.loader, options: babel.options },
    { loader: 'astroturf/loader', options: { extension: '.astroturf.css' } }
  ];
  babel.options = undefined;
  return config;
};

module.exports = override(
  addWebpackModuleRule({
    test: /\.astroturf\.css$/,
    use: ['style-loader', 'astroturf/css-loader'],
  }),
  addAstroturf()
);

The addAstroturf function is a custom CRA override that extends the loader with astroturf, instead of overwriting. Additionally, I found that using astroturf meant import './Foo.css' no longer worked - the custom extension and webpack module rule for astroturf.css work to isolate astroturf from the rest of the build chain.

Here are my dependencies, in case this changes for CRA in the future:

"create-react-app": "^4.0.0",
"astroturf": "^0.10.5",
"customize-cra": "^1.0.0",
"react": "^17.0.1",
"react-app-rewired": "^2.1.6",