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

any solution with angular6?

deepthan avatar Jan 15 '19 01:01 deepthan

I have the same problem.

lake2 avatar Apr 02 '19 03:04 lake2

Bumping this, we dropped Sass and other preprocessors for PostCSS for about 3 years.

ahmadalfy avatar Jul 26 '19 18:07 ahmadalfy

It would be really great to be able to add custom PostCSS plugins into an project utilizing the @angular/cli tooling.

jasonraimondi avatar Nov 22 '19 01:11 jasonraimondi

Here is a great article about how to extend postcss with @angular-builders/custom-webpack I think it will solve the issue for us for now.

https://netbasal.com/customize-webpack-configuration-in-your-angular-application-d09683f6bd22

abierbaum avatar Nov 27 '19 14:11 abierbaum

No, it wont. angular-cli injects own internal postcss plugin to postcss loader. angular-cli -> webpack -> potscss loader -> postcss plugins.

See node_modules/@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/styles.js

unlight avatar Nov 28 '19 18:11 unlight

we had the same issue, since we needed additional loader for loading scss.

We are doing it dirty like this, using @angular-builders/custom-webpack:

module.exports = (config) => {

  // removing old loader
  config.module.rules = Array.from(config.module.rules).filter(e => !`${e.test}`.startsWith('/\\.scss'));

  // Adding proper scss rule with loaders
  config.module.rules.push({
    test: /\.scss$|\.sass$/,
    use: [
      {
        loader: 'postcss-loader',
        options: {
          sourceMap: false,
        }
      },
      {
        loader: 'resolve-url-loader',
        options: {sourceMap: false}
      },
      {
        loader: 'sass-loader',
        options: {sourceMap: false}
      }
    ]
  });

  return config;
};

Would love to get rid of it though

Adding PostCss plugin by Custom webpack builders does not work https://github.com/just-jeb/angular-builders/issues/634 is this valid?

unlight avatar Dec 26 '19 07:12 unlight

didn't realise I wanted PostCSS Plugins until I saw this: https://github.com/larsenwork/postcss-easing-gradients

intellix avatar Jan 09 '20 13:01 intellix

https://github.com/just-jeb/angular-builders/issues/634 and https://github.com/just-jeb/angular-builders/issues/638 contain information on how this can be achieved using the excellent angular-builders.

This isn't something we're looking at doing as a first party option because exposing PostCSS configuration is very much similar to exposing Webpack configuration, insofar as it requires code configuration and is not guaranteed to be isolated. In webpack, even small configuration changes in one place can require larger edits across other loaders and plugins to work correctly.

I agree it's not easy to do with angular-builders, but it is possible. It would be great to have more composable webpack setup in order to better enable third party modifications.

filipesilva avatar Jan 20 '20 11:01 filipesilva

Simply append or prepend rules didn't work for me. The following custom webpack config worked:

const postcssCustomProperties = require('postcss-custom-properties');

module.exports = (config, options) => {

    const scssRule = config.module.rules.find(x => x.test.toString().includes('scss'));
    const postcssLoader = scssRule.use.find(x => x.loader === 'postcss-loader');
    const pluginFunc = postcssLoader.options.plugins;
    const newPluginFunc = function () {
        var plugs = pluginFunc.apply(this, arguments);
        plugs.splice(plugs.length - 1, 0, postcssCustomProperties({ preserve: true }));
        return plugs;
    }
    postcssLoader.options.plugins = newPluginFunc;

    return config;
};

ToniaDemchuk avatar Jan 20 '20 12:01 ToniaDemchuk

I've tried this approach and it did not work for me (angular 9.0.0-rc.7). Build hangs (stuck) on Generating ES5 bundles for differential loading... But looks like plugins injected correctly.

unlight avatar Jan 20 '20 19:01 unlight

@ToniaDemchuk how does your angular.json file looks like do you have a repo that i can refer?

anoopsinghbayes avatar Jan 27 '20 17:01 anoopsinghbayes

@anoopsinghbayes Unfortunately, no public repo I can share to you. Here is angular.json file:

{
    "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
    "version": 1,
    "newProjectRoot": "projects",
    "projects": {
        "MyProject": {
            "root": "",
            "sourceRoot": "src",
            "projectType": "application",
            "prefix": "app",
            "schematics": {
                "@schematics/angular:component": {
                    "style": "scss"
                }
            },
            "architect": {
                "build": {
                    "builder": "@angular-builders/custom-webpack:browser",
                    "options": {
                        "outputPath": "wwwroot",
                        "index": "src/index.html",
                        "main": "src/main.ts",
                        "polyfills": "src/polyfills.ts",
                        "tsConfig": "src/tsconfig.app.json",
                        "assets": [
                            "src/favicon.ico",
                            "src/assets"                            
                        ],
                        "styles": [
                            "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
                            "src/styles.scss",
                            "src/styles/global-styles.scss",
                            "./node_modules/quill-mention/dist/quill.mention.min.css",
                            "./node_modules/quill/dist/quill.core.css",
                            "./node_modules/quill/dist/quill.snow.css"
                        ],
                        "scripts": [],
                        "customWebpackConfig": {
                            "path": "./custom-webpack.config.js",
                            "replaceDuplicatePlugins": true,
                            "mergeStrategies": {
                                "module.rules": "prepend"
                            }
                        }
                    },
                    "configurations": {
                        "production": {
                            "fileReplacements": [
                                {
                                    "replace": "src/environments/environment.ts",
                                    "with": "src/environments/environment.prod.ts"
                                }
                            ],
                            "optimization": true,
                            "outputHashing": "all",
                            "sourceMap": false,
                            "extractCss": true,
                            "namedChunks": false,
                            "aot": true,
                            "extractLicenses": true,
                            "vendorChunk": false,
                            "buildOptimizer": true,
                            "budgets": [
                                {
                                    "type": "initial",
                                    "maximumWarning": "2mb",
                                    "maximumError": "5mb"
                                }
                            ]
                        }
                    }
                },
                "serve": {
                    "builder": "@angular-builders/custom-webpack:dev-server",
                    "options": {
                        "browserTarget": "MyProject:build"
                    },
                    "configurations": {
                        "production": {
                            "browserTarget": "MyProject:build:production"
                        }
                    }
                },
                "extract-i18n": {
                    "builder": "@angular-devkit/build-angular:extract-i18n",
                    "options": {
                        "browserTarget": "MyProject:build"
                    }
                },
                "test": {
                    "builder": "@angular-devkit/build-angular:karma",
                    "options": {
                        "main": "src/test.ts",
                        "polyfills": "src/polyfills.ts",
                        "tsConfig": "src/tsconfig.spec.json",
                        "karmaConfig": "src/karma.conf.js",
                        "styles": [
                            "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
                            "src/styles.scss"
                        ],
                        "scripts": [],
                        "assets": [
                            "src/favicon.ico",
                            "src/assets"
                        ]
                    }
                },
                "lint": {
                    "builder": "@angular-devkit/build-angular:tslint",
                    "options": {
                        "tsConfig": [
                            "src/tsconfig.app.json",
                            "src/tsconfig.spec.json"
                        ],
                        "exclude": [
                            "**/node_modules/**"
                        ]
                    }
                }
            }
        }
    },
    "defaultProject": "MyProject"
}

Angular versions from package.json:

"@angular/animations": "8.2.14",
"@angular/cdk": "8.2.3",
"@angular/common": "8.2.14",
"@angular/compiler": "8.2.14",
"@angular/core": "8.2.14",
"@angular/flex-layout": "8.0.0-beta.27",
"@angular/forms": "8.2.14",
"@angular/material": "8.2.3",
"@angular/platform-browser": "8.2.14",
"@angular/platform-browser-dynamic": "8.2.14",
"@angular/router": "8.2.14",
"@angular-builders/custom-webpack": "8.4.1",
"@angular-builders/dev-server": "7.3.1",
"@angular-devkit/build-angular": "0.803.20",
"@angular/cli": "8.3.20",
"@angular/compiler-cli": "8.2.14",
"@angular/language-service": "8.2.14",

ToniaDemchuk avatar Jan 28 '20 12:01 ToniaDemchuk

I tried something based on what @ToniaDemchuk did, and wasn't able to get it to work. I did some debugging to make sure the plugin was correctly added to the list of postcss plugins, and I was able to get that to work, but the plugin still isn't doing anything.

I have another project using postcss within "plain"(?) webpack config, and the postcss plugins work fine there.

Here's what I have - it fixes a bug in finding the postcss-loader, and it successfully adds a plugin, but there's no evidence that the plugin is doing anything:

angular.json:

 "projects": {
    "(app name)": {
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
...
            "customWebpackConfig": {
              "path": "ng-webpack-ext.config.js"
            },

ng-webpack-ext.config.js :

const combineMediaQueryPlugin = require('postcss-combine-media-query');

/**
 * Patches the webpack postcss-loader plugins function to add the specified postcss
 * plugins, in addition to angular's defaults.
 *
 * @param {object} webpackConfig - The webpack config, created by angular-devkit
 * @param {array} addPlugins - An array of postcss plugins to insert at the beginning of the postcss plugins
 */
function patchWebpackPostcssPlugins(webpackConfig, addPlugins) {
  const webpackScssRule = webpackConfig.module.rules.find(x => x.test.toString().includes('scss'));
  if (!webpackScssRule) {
    console.warn('[ng-webpack-ext.config.js]: No scss rule found');
  }
  else {
    const postcssLoader = webpackScssRule.use.find(x => x.loader.includes('postcss-loader'));
    const pluginFunc = postcssLoader.options.plugins;
    const newPluginFunc = function () {
      let plugins = pluginFunc.apply(this, arguments);
      plugins = plugins.concat(addPlugins);
      console.dir(plugins); // Shows the plugins
      return plugins;
    }
    postcssLoader.options.plugins = newPluginFunc;
  }
};

/** Function returning webpack config. */
module.exports = (config, options) => {
  patchWebpackPostcssPlugins(config, [combineMediaQueryPlugin()]);

  return config;
};

Looking at the current angular-cli code, it looks like there's an OptimizeCssWebpackPlugin which wraps cssnano and postcss. That runs as a webpack minimizer.

The console.dir line above show that my plugin is included in the array, after the others created by angular's plugin creator:

[
  [Function (anonymous)] {
    postcssPlugin: 'postcss-import',
    postcssVersion: '7.0.27'
  },
  [Function (anonymous)] {
    postcssPlugin: 'postcss-cli-resources',
    postcssVersion: '7.0.27'
  },
  [Function: plugin] {
    options: {},
    browsers: undefined,
    info: [Function (anonymous)],
    postcssPlugin: 'autoprefixer',
    postcssVersion: '7.0.27'
  },
  [Function (anonymous)] {
    postcssPlugin: 'postcss-combine-media-query',
    postcssVersion: '7.0.27'
  }
]

I'm pretty much stuck figuring out why the postcss plugin isn't being used. I've about hit my limit on painful troubleshooting for one day.

johncrim avatar May 23 '20 00:05 johncrim

Any progress update on this feature? Almost 3 years since it was suggested. I am dropping SASS and going PostCSS. Right now it looks like I will have to switch to React to do that.

GuerrillaCoder avatar Aug 23 '20 19:08 GuerrillaCoder

as mentioned above and in this article I had no problem integrating postcss/tailwindcss.

The integration is straightforward and all one has to do is provide the custom build part themselves, no need to get the hands dirtly with Angular Cli internals.

banjankri avatar Nov 20 '20 13:11 banjankri

@banjankri getting tailwind to work is not a problem, even with material. But we still face an issue when debugging css in chrome. All imported styles in styles.scss gets inlined. You don't see the actual file in chrome. I would love to add just the plugin instead of override the webpack config

CodewindOnGithub avatar Nov 27 '20 14:11 CodewindOnGithub

for applying custom post-css plugins I found a solution in this ticket: https://github.com/just-jeb/angular-builders/issues/638

CodewindOnGithub avatar Nov 30 '20 08:11 CodewindOnGithub

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

extra-webpack.config.js :

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

  const globalStylesPostcssOptionsCreator = globalStylesPostcssLoaderOptions.postcssOptions;

  globalStylesPostcssLoaderOptions.postcssOptions = (loader) => {
    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: https://github.com/just-jeb/angular-builders/issues/638#issuecomment-564515958. The global styles loader chain uses an include, while the components' uses an exclude.

EDIT: I changed the config to js as @angular-builders/custom-webpack has an open issue with typescript and karma (https://github.com/just-jeb/angular-builders/issues/749).

georgiyordanov avatar Dec 10 '20 07:12 georgiyordanov