angular-cli icon indicating copy to clipboard operation
angular-cli copied to clipboard

Specify custom PostCSS plugins

Open ghost opened this issue 9 years ago • 51 comments

Bug Report or Feature Request (mark with an x)

- [ ] bug report -> please search issues before submitting
- [x] feature request

Versions.

@angular/cli: 1.4.9 node: 6.11.4 os: linux x64 @angular/animations: 4.4.6 @angular/common: 4.4.6 @angular/compiler: 4.4.6 @angular/core: 4.4.6 @angular/forms: 4.4.6 @angular/http: 4.4.6 @angular/platform-browser: 4.4.6 @angular/platform-browser-dynamic: 4.4.6 @angular/router: 4.4.6 @angular/cli: 1.4.9 @angular/compiler-cli: 4.4.6 @angular/language-service: 4.4.6 typescript: 2.3.4

Desired functionality.

I would like the ability to specify custom postCss plugins, without having to eject the angular webpack.config.js file.

Mention any other details that might be useful.

This would enable frameworks like TailwindCSS (https://tailwindcss.com) and other useful PostCSS plugins through the CLI without having to deal with the ejected webpack config file.

ghost avatar Nov 09 '17 20:11 ghost

If anyone needs it, here is a working tailwindcss config for @angular/[email protected] and @angular-builders/[email protected].

extra-webpack.config.ts :

export default (config: any) => {
  const globalStylesPostcssLoaderOptions = config.module.rules
    .find((r: any) => r.include && r.test && r.test.toString().includes('\\.scss$'))
    .use.find((u: any) => u.loader.includes('postcss-loader')).options;

  const globalStylesPostcssOptionsCreator = globalStylesPostcssLoaderOptions.postcssOptions;

  globalStylesPostcssLoaderOptions.postcssOptions = (loader: any) => {
    const postcssOptions = globalStylesPostcssOptionsCreator(loader);
    postcssOptions.plugins.splice(postcssOptions.plugins.length - 1, 0, require('tailwindcss'));

    return postcssOptions;
  };

  return config;
};

The important part is to modify only the global styles loader chain as explained here: just-jeb/angular-builders#638 (comment). The global styles loader chain uses an include, while the components' uses an exclude.

If anyone is wondering why it fails with Tailwind 2... Angular still uses PostCSS 7. see https://tailwindcss.com/docs/installation#post-css-7-compatibility-build

antoinebrault avatar Dec 14 '20 20:12 antoinebrault

@antoinebrault @angular/[email protected] uses PostCSS 8 https://github.com/angular/angular-cli/commit/48c7a85f0ae8ad760c9783ec87f9746741d24828

@georgiyordanov can confirm that your snippet works with @angular/[email protected] and @angular-builders/[email protected]

vltansky avatar Dec 27 '20 15:12 vltansky

Maybe can be useful for somebody: helper function to add postcss plugins at specific index or before/after plugin (e.g adding tailwind before autoprefixer) to all angular postcss options (sass, scss, css, stylus, less). You can choose if to add to global and/or component levels files. here is example repo: https://github.com/vltansky/tailwind-ng11

function patchWebpackPostcssPlugins({
  webpackConfig,
  addPlugins = [],
  pluginName = null,
  append = false,
  atIndex = null,
  components = true,
  global = true,
}) {
  const position = append ? 1 : 0;
  webpackConfig.module.rules.map((rule) => {
    if (!(rule.use && rule.use.length > 0) || (!components && rule.exclude) || (!global && rule.include)) {
      return rule;
    }
    rule.use.map((useLoader) => {
      if (!(useLoader.options && useLoader.options.postcssOptions)) {
        return useLoader;
      }
      const postcssOptions = useLoader.options.postcssOptions;
      useLoader.options.postcssOptions = (loader) => {
        const _postcssOptions = postcssOptions(loader);
        const pluginIndex =
          atIndex !== null
            ? atIndex
            : _postcssOptions.plugins.findIndex(
                ({ postcssPlugin }) =>
                  postcssPlugin && pluginName && postcssPlugin.toLowerCase() === pluginName.toLowerCase()
              );
        if (pluginName && pluginIndex === -1) {
          console.warn(`${pluginName} not found in postcss plugins`);
        }
        const insertIndex =
          pluginIndex >= 0
            ? Math.min(Math.max(pluginIndex, 0), _postcssOptions.plugins.length)
            : _postcssOptions.plugins.length;
        _postcssOptions.plugins.splice(insertIndex + position, 0, ...addPlugins);
        return _postcssOptions;
      };
      return useLoader;
    });
    return rule;
  });
}

module.exports = (config) => {
  const isProd = config.mode === "production";
  const tailwindConfig = require("./tailwind.config.js")(isProd);
  patchWebpackPostcssPlugins({
    webpackConfig: config,
    addPlugins: [require("tailwindcss")(tailwindConfig)],
    pluginName: "autoprefixer",
    // global: false,
    // components: false,
    // atIndex: 2,
    // append: false,
  });
  return config;
};

vltansky avatar Dec 27 '20 21:12 vltansky

@antoinebrault @angular/[email protected] uses PostCSS 8 48c7a85

@georgiyordanov can confirm that your snippet works with @angular/[email protected] and @angular-builders/[email protected]

@vltansky As far as I can tell, @angular/[email protected] still uses PostCSS 7. It looks like PostCSS 8 will be included in @angular/[email protected].

Yep, the config above also works with @angular/[email protected] and @angular-builders/[email protected]. I've updated my comment.

georgiyordanov avatar Dec 28 '20 09:12 georgiyordanov

@georgiyordanov right, looks like although postcss have been updated in @angular/cli/package.json and released,@angular-devkit/build-angular/package.json is updated to postcss 8 but not released https://github.com/angular/angular-cli/commit/94e0d6a8f76b9aa9124d1368a4536f0122beec5a But somehow tailwind build works fine for me. How is that?

vltansky avatar Dec 28 '20 09:12 vltansky

We are currently running a survey about PostCSS. If there are specific plugins that you'd like Angular CLI to support, please let us know. Once the survey is concluded we'll post an update on the results and the next steps here.

kyliau avatar Jan 14 '21 17:01 kyliau

Based on the survey results, 90% of the participants wanted Tailwind CSS, and 37% wanted Purge CSS. The signal was loud and clear, so we have added Tailwind support in #19935, and it'll be released in v11.2 scheduled for Feb 10, 2021.

As for PurgeCSS, supporting it is somewhat tricky due to the risk of breaking applications. After some thorough discussion with the Angular Components team, we think it is best to separate the problem space into first-party code and third-party code. For first-party code, since developers know their own code best, it is better that CLI provide a checker to detect unused CSS, and let developers decide if they want to remove (more importantly, whether it is safe to remove) the CSS themselves. This applies to both component stylesheets and global stylesheets. For third-party code, removing unused CSS is necessary in some libraries that do not provide fine grained stylesheets. However, this can be done post-build, and does not necessarily require integration with CLI. We are working on this, and will publish some guides / examples soon.

We maintain our stance that exposing PostCSS configuration is not a scalable solution in the long term, as explained in https://github.com/angular/angular-cli/issues/8427#issuecomment-576234801. Going forward, while we are not able to support every PostCSS plugin out there, we will continue to review different use cases on an individual basis, and make decision based on developer feedback and the current landscape of web development. Please open a new issue if there's a specific plugin you'd like CLI to support. I'll close this issue for now, thank you all for the feedback!

Screen Shot 2021-02-04 at 9 15 47 AM

kyliau avatar Feb 04 '21 19:02 kyliau

Hi All - nice work on landing this!

Quick question: is there a way to disable the automatic detection of Tailwind?

I want to continue using my custom webpack builder configuration for tailwind but also want to be on v11.2

matAtGitHub avatar Feb 15 '21 21:02 matAtGitHub

@mattAtPropertyMe rename your tailwind.config.js to any other name

vltansky avatar Feb 15 '21 21:02 vltansky

Thanks @vltansky confirming your suggestion worked, however unfortunately it breaks VSCode Tailwind IntelliSense.

The good news is, renaming the file to tailwind.js fixes everything, reasoning below.

The Angular CLI only references the file tailwind.config.js and the Tailwind IntelliSense extension looks for both tailwind.config.js and tailwind.js

Thanks again.

matAtGitHub avatar Feb 16 '21 01:02 matAtGitHub

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.