astroturfcss / astroturf

Better Styling through Compiling: CSS-in-JS for those that want it all.
https://astroturfcss.github.io/astroturf/
MIT License
2.28k stars 60 forks source link

Add function as posible value of extension option #674

Closed yusuphgammut closed 3 years ago

yusuphgammut commented 3 years ago

I was setting up a project with Astroturf and realized that it would be very useful and powerful if the developer could set a function as the value of the extension option in the configurations. This function gets the current complete file path being processed as an argument and should return the desired extension for the extracted file.

This simple addition enables a lot of flexibility for users that want to trigger different build paths depending on the file name or folder location of the files containing the styles. For example, I can configure css-loader to treat files differently based on name with the modules.mode option and then, configure astroturf to name my files ending in global.js to be exported as global.css if I want those to be processed by CSS Modules with a default global scope, and local.js to local.css if I want them to be processed with default local scope. This is just one example but the possible configurations and build workflows it opens are quite big, specially when used along other PostCSS plugins and CSSModules.

For this to work we only need to refactor the createFileName function inside src/utils/createFileName.js to the following:

export default function createFilename(hostFile, { extension = '.css' }, id) {
  let base, finalExt;

  switch (typeof extension) {
    case 'function':
      finalExt = extension(hostFile);
      break;
    case 'string':
      finalExt = extension;
      break;
    default:
      throw new Error(
        'The extension option provided is not of type String or Function. ' +
          'Please ensure you provide an extention option of any of those types.',
      );
  }

  if (getNameFromFile(hostFile) === id) base = id;
  else base = `${basename(hostFile, extname(hostFile))}-${id}`;

  return join(dirname(hostFile), base + finalExt);
}

Let me know your opinion about this addition and I can create a PR including unit tests as well. I tried to create it but seems I don't have permissions.

git push origin feature/extension-option-function
ERROR: Permission to 4Catalyzer/astroturf.git denied to yusuphgammut.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
jquense commented 3 years ago

you can already do this by providing a getFileName() option i believe

yusuphgammut commented 3 years ago

Yeah, that's what I needed. It would be useful if you can add that to the list of options in the README file. Right now it's only shown in the last example. Thanks @jquense .