posthtml / posthtml-css-modules

Use CSS modules in HTML

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Silent fails when using gulp and 'css-modules' attribute not pointing correctly

awarn opened this issue · comments

I ran up against a problem that did not raise any error with this gulp task that processes some template files with CSS modules:

//gulpfile.js
...
gulp.task('templates', function() {
  let posthtml = require('gulp-posthtml');
  return gulp.src('src/templates/**/*.html')
    .pipe( posthtml([ 
        require('posthtml-css-modules')('./.tmp/css-modules/json/')
        ]) )
    .pipe( gulp.dest('build/templates/') );
})
...

Firstly, if './.tmp/css-modules/json/' does not give require-able json resources, the task simply quits without any notice. I might be able to deal with that in the gulpfile, somehow, but it was a bit mystifying on setup.

What is worse, though, is that if I in the template files use a value for the css-module attribute, like so:

<div css-module="article.symbol">

If .symbol does not exist in the article module, the process also fails without notice. It works fine if done right, but tracing an error is a headache.

I'm using Twig (not HTML) for the template files, if that is relevant in the latter case.

PS: Great plugin - I'm finding it very handy trying to use CSS Modules in Twig files without actually rendering them (which is done on requests by the CMS). Maybe there is a standard way of doing that, but this is the closest I've found.

Thanks @awarn!

To catch all errors from PostHTML and its plugins just add a listener to posthtml:

//gulpfile.js
...
gulp.task('templates', function() {
  let posthtml = require('gulp-posthtml');
  return gulp.src('src/templates/**/*.html')
    .pipe( posthtml([ 
        require('posthtml-css-modules')('./.tmp/css-modules/json/')
        ]).on('error', function(err) { console.error(err); }) )
    .pipe( gulp.dest('build/templates/') );
})
...

Another way is to catch errors from all streams via gulp-plumber:

//gulpfile.js
var plumber = require('gulp-plumber');
...
gulp.task('templates', function() {
  let posthtml = require('gulp-posthtml');
  return gulp.src('src/templates/**/*.html')
    .pipe(plumber())
    .pipe( posthtml([ 
        require('posthtml-css-modules')('./.tmp/css-modules/json/')
        ]) )
    .pipe( gulp.dest('build/templates/') );
})
...