Search code examples
cssgulppostcsscss-modules

Using postcss-conditionals with mixins


I'm having an issue converting my postcss conditionals to css. I'm using gulp to process the files and output a css file. Everything seems to be working up until the point that I try to convert the conditionals (see below).

Here is my gulp file:

const postcss = require('gulp-postcss');
const gulp = require('gulp');
const rename = require('gulp-rename');

gulp.task('generate-css', function () {
  var plugins = [
    require('postcss-import'),
    require('postcss-mixins'),
    require('postcss-nested'),
    require('postcss-simple-vars'),
    require('postcss-calc'),
    require('postcss-conditionals'),
    // require('cssnano'), -> commented out so that I can see what is being converted correctly
  ];
  return gulp
    .src('./src/pages/test/*.css')
    .pipe(postcss(plugins))
    .pipe(
      rename(function (path) {
        path.dirname = './src/pages/' + path.dirname;
        path.basename = 'testingStyles.module';
        path.extname = '.css';
      }),
    )
    .pipe(gulp.dest('.'));
});

Here is a simplified version of my postcss file:

@import '../../theme/_mixins.css';
@import '../../theme/_variables.css';

.myClass {
  @mixin mixinOne;
  @mixin mixinTwo bottom, 10;

  &__icon {
    @mixin SVG logo_url, $my-color;
  }
}

The issue that (I think) that I am experiencing is that the mixins (which are imported) are not processed before postcss-conditionals tries to remove the @if statements.

This gives me this error:

postcss-conditionals: .../_mixins.css:4:3: Failed to parse expression
  3 | @define-mixin mixinOne $paramOne, $paramTwo {
> 4 |   @if $direction == all {
    |   ^
  5 |     margin: calc($spacer * $(factor));
  6 |   }

If I remove the postcss-conditionals plugin I get a css file with all of the previous plugins in the list succussfully applied (no nesting, vars correctly substituted, calcs transformed etc). There are no @define-mixins in the output css file if I remove the postcss-conditionals plugin.

I'm at a bit of a loss as to how to make sure that the @define-mixins are processed before it tries to remove the conditionals (the order of the plugins seems to be correct to me).

If anyone has some insight into what I'm doing wrong that would be greatly appreciated!


Solution

  • maybe there is some way to process the plugins in two passes? E.g. first ['postcss-import', 'postcss-mixins'], then the rest? That would at least (dis)prove your theory