Error in plugin gulp postcss

The error is coming from the postcss plugin, I think I may have written it incorrectly. I'm trying to add cssnano and autoprefixer to the postcss plugin. gulp/node_modules/gulp-postcss/node_modu...

The error is coming from the postcss plugin, I think I may have written it incorrectly.

I’m trying to add cssnano and autoprefixer to the postcss plugin.

gulp/node_modules/gulp-postcss/node_modules/postcss/lib/processor.js:143
        throw new Error(i + ' is not a PostCSS plugin');
        ^

Error: [object Object] is not a PostCSS plugin
    at Processor.normalize (/Applications/XAMPP/xamppfiles/htdocs/sites/gulp/node_modules/gulp-postcss/node_modules/postcss/lib/processor.js:143:15)
    at new Processor (/Applications/XAMPP/xamppfiles/htdocs/sites/gulp/node_modules/gulp-postcss/node_modules/postcss/lib/processor.js:51:25)
    at postcss (/Applications/XAMPP/xamppfiles/htdocs/sites/gulp/node_modules/gulp-postcss/node_modules/postcss/lib/postcss.js:73:10)
    at Transform.stream._transform (/Applications/XAMPP/xamppfiles/htdocs/sites/gulp/node_modules/gulp-postcss/index.js:47:5)
    at Transform._read (_stream_transform.js:167:10)
    at Transform._write (_stream_transform.js:155:12)
    at doWrite (_stream_writable.js:300:12)
    at writeOrBuffer (_stream_writable.js:286:5)
    at Transform.Writable.write (_stream_writable.js:214:11)
    at DestroyableTransform.ondata (/Applications/XAMPP/xamppfiles/htdocs/sites/gulp/node_modules/gulp-sass/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:531:20)
Mac-a45e60e72dad:gulp JoeKonst$ 

My code:

// Dependancies
var gulp = require('gulp'),
    browserSync = require('browser-sync'),
    plumber = require('gulp-plumber'),
    autoprefixer = require('gulp-autoprefixer'),
    uglify = require('gulp-uglify'),
    compass = require('gulp-compass'),
    rename = require('gulp-rename'),
    nano = require('cssnano'),
    del = require('del'),
    postcss = require('gulp-postcss'),
    sass = require('gulp-sass');

// Styles
gulp.task('styles', function(){
    gulp.src('sass/main.scss')
    .pipe(sass())
    .pipe(postcss([autoprefixer({browsers: ['last 2 versions']}), nano()]))
    .pipe(gulp.dest('css/'));

    gulp.watch('sass/**/*.scss', ['styles']);
});

// Tasks
gulp.task('default', ['styles']);

Содержание

  1. Stops after «Error in plugin ‘gulp-postcss’ » #42
  2. Comments
  3. Footer
  4. Expected a pseudo-class or pseudo-element #1246
  5. Comments
  6. Fails silently with missing file and postcss-import #32
  7. Comments
  8. given:
  9. running:
  10. resulting:

Stops after «Error in plugin ‘gulp-postcss’ » #42

Whenever there is an error, like importing file that does not exist (wrong path), I get this error which stops gulp:

Really annoying causing me to restart my tasks every time css error is made. Am I doing something wrong?

The text was updated successfully, but these errors were encountered:

I’m having a similar problem using gulp-postcss , gulp-plumber , and gulp-watch together — task shown below. When the task encounters a CSS error, the task remains open and the error is logged per the warn error handler passed in, so all is good so far. But the build files aren’t updated with any changes made to the source files, like fixing the error.

gulp-watch does still continue to log that changes were detected in the source files; they just don’t get processed anymore unless I restart the task over again.

Has anyone found a solution/workaround for this yet?

I have the same issue.

I have this problem, but nobody resolved it as I see.

Bad fix:
Will work with gulp-notify https://www.npmjs.com/package/gulp-notify
import notify from ‘gulp-notify’; and
Instead .pipe(plumber()) insert .pipe(plumber(< errorHandler: notify.onError(‘Error: ‘) >))

I don’t know why it works, I found it when I wanted to delete gulp-notify , he has his own problems (with notifications).

Just notice the same. Solutions?

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Expected a pseudo-class or pseudo-element #1246

This is my first time raising an issue.

I am studying Git a Web Developer and added post css library. Now, facing error as follow —

`Error in plugin «gulp-postcss»
Message:
Expected a pseudo-class or pseudo-element.
Details:
fileName: /Users/Vikram/Documents/DevLab/travel-site/app/assets/styles/styles.css

Stack:
Error: Expected a pseudo-class or pseudo-element.
at Root._error (/Users/Vikram/Documents/DevLab/travel-site/node_modules/postcss-selector-parser/dist/parser.js:182:24)
at Root.error (/Users/Vikram/Documents/DevLab/travel-site/node_modules/postcss-selector-parser/dist/selectors/root.js:43:25)
at Parser.error (/Users/Vikram/Documents/DevLab/travel-site/node_modules/postcss-selector-parser/dist/parser.js:666:25)
at Parser.expected (/Users/Vikram/Documents/DevLab/travel-site/node_modules/postcss-selector-parser/dist/parser.js:994:25)
at Parser.pseudo (/Users/Vikram/Documents/DevLab/travel-site/node_modules/postcss-selector-parser/dist/parser.js:799:25)
at Parser.parse (/Users/Vikram/Documents/DevLab/travel-site/node_modules/postcss-selector-parser/dist/parser.js:955:22)
at Parser.loop (/Users/Vikram/Documents/DevLab/travel-site/node_modules/postcss-selector-parser/dist/parser.js:923:18)
at new Parser (/Users/Vikram/Documents/DevLab/travel-site/node_modules/postcss-selector-parser/dist/parser.js:174:14)
at Processor._root (/Users/Vikram/Documents/DevLab/travel-site/node_modules/postcss-selector-parser/dist/processor.js:47:22)
at Processor._runSync (/Users/Vikram/Documents/DevLab/travel-site/node_modules/postcss-selector-parser/dist/processor.js:83:25)
at Processor.processSync (/Users/Vikram/Documents/DevLab/travel-site/node_modules/postcss-selector-parser/dist/processor.js:177:27)
at parse (/Users/Vikram/Documents/DevLab/travel-site/node_modules/postcss-nested/index.js:9:9)
at /Users/Vikram/Documents/DevLab/travel-site/node_modules/postcss-nested/index.js:39:18
at Array.forEach ()
at /Users/Vikram/Documents/DevLab/travel-site/node_modules/postcss-nested/index.js:38:21
at Array.forEach ()`

The stack clearly mentions the error to be found in postcss-nested/index.js. I tried reinstalling the postcss but it doesn’t help.

Due to this error, any styles further added are not working.

The text was updated successfully, but these errors were encountered:

Источник

Fails silently with missing file and postcss-import #32

But when using gulp-postcss w/ postcss-import and you try to import a missing file, the gulp task never finishes and postcss processing seems to abort.

The text was updated successfully, but these errors were encountered:

@timkelty, given this gulpfile:

and the following css file src/style.css :

I get the following output in the console:

So I guess it is working as expected and the error is passed as a stream event.

@timkelty got no further input from your side, may I close this?

I’ll test right now and see what’s going on with my environment.

Gulp-postcss (not sure, maybe postcss itself) seem to always fail silently. Any error with missing paths in some of the plugins causes it silently fail. It should print the error, this hardens debugging very much.

Issues noticed with cssgrace (when url points to missing file), postcss-assets with same problem of resolving paths.

This is how it looks like:

Sticking gulp-plumber in the pipe right before postcss takes care of everything for me. @olegstepura I would give that a try if you haven’t yet.

It helps. Thanks!

gulp-postcss has a test for correct stream error that you can listen to and log to console.

It also tests that in case of cssSyntaxError it should emit a pretty error from postCSS instead of regular js stack trace.

According to gulp plugin guidelines an error should not be thrown, but it should be emitted.

Well, stack trace is helpful when you don’t know who did thrown an exception. In case of postcss plugins exceptions are no longer thrown by some gulp plugins, it’s thrown by postcss plugins that know nothing about gulp.

@olegstepura of course stack trace is helpful, and it is there for non-cssSyntaxErrors, so feel free to subscribe to the stream error event and use your preferred method of displaying the errors. Tests should give you a hint of how to capture stream errors, or use gulp-plumber with gulp-postcss.

I’m very exceited of the project postcss itself. but silent fails almost made stop trying. Also it seems some postcss plugins are still bad quality, plugin order matters, and so on. but thanks to @timkelty for pointing to gulp-plumber , I was thinking plumber was designed for other reasons.

This is an offtop, but don’t you know if it is possible to tell plumber to print stack?

Ok, seems the best way is to setup custom error logging function

@olegstepura feel free to open pull request to improve the quality of certain postcss plugins. This repository is only related to gulp plugin.

Hoping this is the right place to ask, but what is the best way to surface warnings from postcss plugins now?

For example postcss-bem-linter uses the warning class as seen here. But I don’t think this triggers an error in a stream?

Have tried using postcss-log-warning with throwError set to true but still doesn’t seem to throw an error.

@simonsmith I think that warnings should behave differently from the errors, as far as I understand, according to guidelines they should be output in the console rather than emitted as errors.

I’m also facing this issue, but plumber doesn’t seem to be helping:

given:

running:

resulting:

I also tried using postcss-log-warnings, now I get this:

in addition, postcss-import IS finding these files:

/projects/LevelEleven/ui-kit/gulpfile.js [14:58:26] Starting ‘styles:toolkit’. [ ‘/Users/vince/projects/LevelEleven/ui-kit/src/assets/toolkit/styles/toolkit.css’, ‘/Users/vince/projects/LevelEleven/ui-kit/node_modules/suitcss-components-grid/index.css’, ‘/Users/vince/projects/LevelEleven/ui-kit/node_modules/suitcss-components-grid/lib/grid.css’, ‘/Users/vince/projects/LevelEleven/ui-kit/src/assets/toolkit/styles/dude.css’ ] ** postcss-log-warnings: warnings were found **»>

@VinSpee sorry, I’m super busy and will only be able to look into this on the weekend.

No problem! I appreciate you even looking at all. On a second glance, I think the issue may be in gulp-sourcemaps or maybe even gulp-autoprefixer because if I remove them, the build works. I’ll close for now.

@VinSpee that issue is about postcss-log-warnings I believe, not gulp-postcss. See: davidtheclark/postcss-log-warnings#6 — working on figuring it out.

Источник

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

gulpfile.js

const
  gulp          = require('gulp'),
  gulpsass      = require('gulp-sass'),
  browsersync   = require("browser-sync"),
  babel         = require('gulp-babel'),
  phpConnect    = require('gulp-connect-php'),
  concat        = require('gulp-concat'),
  concatCSS     = require('gulp-concat-css'),
  uglify        = require('gulp-uglifyjs'),
  cssnano       = require('gulp-cssnano'),
  rename        = require('gulp-rename'),
  del           = require('del'),
  imagemin      = require('gulp-imagemin'),
  pngquant      = require('imagemin-pngquant'),
  cache         = require('gulp-cache'),
  autoprefixer  = require('gulp-autoprefixer'),
  htmlmin       = require('gulp-htmlmin'),

function gulpSass() {
  return gulp
    .src('assets/sass/**/*.sass')
    .pipe(gulpsass({ outputStyle: "expanded" }))
    .pipe(autoprefixer(['last 15 versions', '> 1%', 'ie 8', 'ie 7'], {cascade: true}))
    .pipe(gulp.dest('assets/css'))
    .pipe(browsersync.stream());
}

function libsJs() {
  return gulp.src([
    'assets/libs/jquery-3.3.1.min.js',
    'assets/libs/bootstrap-4.3.1-dist/js/bootstrap.js',
    'assets/libs/validator.min.js'
  ])
    .pipe(concat('libs.min.js'))
    .pipe(uglify({
      toplevel: true
    }))
    .pipe(gulp.dest('assets/js'))
}

function scripts(){
  return gulp
    .src(['assets/js/main.js', 'assets/js/index.js'])
    .pipe(babel({
      presets: ['@babel/env']
    }))
    .pipe(gulp.dest('assets/scripts'))
}

function libsCss() {
  return gulp.src([
    'assets/libs/bootstrap-4.3.1-dist/css/bootstrap.css',
    'assets/css/animate.css'
  ])
    .pipe(concatCSS('libs.css'))
    .pipe(gulp.dest('assets/css'))
    .pipe(cssnano())
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('assets/css'))
}

function browserSync(done) {
  phpConnect.server({
    port: 8000,
    notify: false,
    keepalive: true,
    base: "./"
  }, function (){
    browsersync({
      proxy: '127.0.0.1:8000/'
    });
  });
  done();
}

function clean() {
  return del(["dist"]);
}
function cleanES() {
  return del(["assets/script"]);
}
function clear() {
  return cache.clearAll();
}

function images() {
  return gulp
    .src("assets/images/**/*")
    .pipe((cache(
      imagemin([
        imagemin.gifsicle({ interlaced: true }),
        imagemin.jpegtran({ progressive: true }),
        imagemin.optipng({ optimizationLevel: 5 }),
        imagemin.svgo({
          plugins: [
            {
              removeViewBox: false,
              collapseGroups: true,
              use: [pngquant()]
            }
          ]
        })
      ])))

    )
    .pipe(gulp.dest('dist/assets/images'));
}

function watchFiles(done) {
  gulp.watch("./**/*.php", reload);
  gulp.watch('assets/sass/**/*.sass', gulp.parallel(gulpSass));
  gulp.watch('assets/js/**/*.js', reload);
  gulp.watch('*.html', reload);
  done();
}

function buildFiles(done) {
  gulp.src([
    'assets/css/main.css',
    'assets/css/libs.min.css'
  ])
    .pipe(cssnano())
    .pipe(gulp.dest('dist/assets/css'));

  gulp.src(
    'assets/js/libs.min.js')
    .pipe(gulp.dest('dist/assets/js'));

  gulp.src(['assets/scripts/main.js'])
    .pipe(uglify())
    .pipe(gulp.dest('dist/assets/scripts'));

  gulp.src(['assets/scripts/config-contact.js'])
    .pipe(uglify({
      toplevel: true
    }))
    .pipe(gulp.dest('dist/assets/scripts'));

  gulp.src('static**!/!*')
    .pipe(gulp.dest('dist'));

  gulp.src('php**!/!*')
    .pipe(gulp.dest('dist'));

  gulp.src('*.html')
    .pipe(htmlmin({collapseWhitespace: true}))
    .pipe(gulp.dest('dist'));

  gulp.src('*.txt')
    .pipe(gulp.dest('dist'));

  gulp.src('*.xml')
    .pipe(gulp.dest('dist'));

  gulp.src('.htaccess')
    .pipe(gulp.dest('dist'));
  done();
}
const watch = gulp.series(watchFiles, gulp.parallel(cleanES, browserSync, scripts, libsJs, libsCss));
const build = gulp.series(clean, gulp.parallel(buildFiles, images, libsJs));

exports.clean = clean;
exports.clean = cleanES;
exports.clear = clear;
exports.watch = watch;
exports.build = build;
exports.default = watch;

function reload(done) {
  browsersync.reload();
  done();
}

Вылетает ошибка Error in plugin «gulp-cssnano»
Message:
postcss-svgo: Error in parsing SVG: Unquoted attribute value

И еще проблема, у меня sass не стримит а релоадит

postcss / gulp-postcss
Goto Github
PK

View Code? Open in Web Editor
NEW

766.0
20.0
75.0
102 KB

Pipe CSS through PostCSS processors with a single parse

License: MIT License

JavaScript 100.00%
postcss
javascript
gulp-plugin

gulp-postcss’s Introduction

Build Status
Coverage Status

PostCSS gulp plugin to pipe CSS through
several plugins, but parse CSS only once.

Install

$ npm install --save-dev postcss gulp-postcss

Install required postcss plugins separately. E.g. for autoprefixer, you need to install autoprefixer package.

Basic usage

The configuration is loaded automatically from postcss.config.js
as described here,
so you don’t have to specify any options.

var postcss = require('gulp-postcss');
var gulp = require('gulp');

gulp.task('css', function () {
    return gulp.src('./src/*.css')
        .pipe(postcss())
        .pipe(gulp.dest('./dest'));
});

Passing plugins directly

var postcss = require('gulp-postcss');
var gulp = require('gulp');
var autoprefixer = require('autoprefixer');
var cssnano = require('cssnano');

gulp.task('css', function () {
    var plugins = [
        autoprefixer({browsers: ['last 1 version']}),
        cssnano()
    ];
    return gulp.src('./src/*.css')
        .pipe(postcss(plugins))
        .pipe(gulp.dest('./dest'));
});

Using with .pcss extension

For using gulp-postcss to have input files in .pcss format and get .css output need additional library like gulp-rename.

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

gulp.task('css', function () {
    return gulp.src('./src/*.pcss')
        .pipe(postcss())
        .pipe(rename({
          extname: '.css'
        }))
        .pipe(gulp.dest('./dest'));
});

This is done for more explicit transformation. According to gulp plugin guidelines

Your plugin should only do one thing, and do it well.

Passing additional options to PostCSS

The second optional argument to gulp-postcss is passed to PostCSS.

This, for instance, may be used to enable custom parser:

var gulp = require('gulp');
var postcss = require('gulp-postcss');
var nested = require('postcss-nested');
var sugarss = require('sugarss');

gulp.task('default', function () {
    var plugins = [nested];
    return gulp.src('in.sss')
        .pipe(postcss(plugins, { parser: sugarss }))
        .pipe(gulp.dest('out'));
});

Using a custom processor

var postcss = require('gulp-postcss');
var cssnext = require('postcss-cssnext');
var opacity = function (css, opts) {
    css.walkDecls(function(decl) {
        if (decl.prop === 'opacity') {
            decl.parent.insertAfter(decl, {
                prop: '-ms-filter',
                value: '"progid:DXImageTransform.Microsoft.Alpha(Opacity=' + (parseFloat(decl.value) * 100) + ')"'
            });
        }
    });
};

gulp.task('css', function () {
    var plugins = [
        cssnext({browsers: ['last 1 version']}),
        opacity
    ];
    return gulp.src('./src/*.css')
        .pipe(postcss(plugins))
        .pipe(gulp.dest('./dest'));
});

Source map support

Source map is disabled by default, to extract map use together
with gulp-sourcemaps.

return gulp.src('./src/*.css')
    .pipe(sourcemaps.init())
    .pipe(postcss(plugins))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('./dest'));

Advanced usage

If you want to configure postcss on per-file-basis, you can pass a callback
that receives vinyl file object and returns
{ plugins: plugins, options: options }. For example, when you need to
parse different extensions differntly:

var gulp = require('gulp');
var postcss = require('gulp-postcss');

gulp.task('css', function () {
    function callback(file) {
        return {
            plugins: [
                require('postcss-import')({ root: file.dirname }),
                require('postcss-modules')
            ],
            options: {
                parser: file.extname === '.sss' ? require('sugarss') : false
            }
        }
    }
    return gulp.src('./src/*.css')
        .pipe(postcss(callback))
        .pipe(gulp.dest('./dest'));
});

The same result may be achieved with
postcss-load-config,
because it receives ctx with the context options and the vinyl file.

var gulp = require('gulp');
var postcss = require('gulp-postcss');

gulp.task('css', function () {
    var contextOptions = { modules: true };
    return gulp.src('./src/*.css')
        .pipe(postcss(contextOptions))
        .pipe(gulp.dest('./dest'));
});
module.exports = function (ctx) {
    var file = ctx.file;
    var options = ctx.options;
    return {
        parser: file.extname === '.sss' ? : 'sugarss' : false,
        plugins: {
           'postcss-import': { root: file.dirname }
           'postcss-modules': options.modules ? {} : false
        }
    }
})

Changelog

  • 9.0.1

    • Bump postcss-load-config to ^3.0.0
  • 9.0.0

    • Bump PostCSS to 8.0
    • Drop Node 6 support
    • PostCSS is now a peer dependency
  • 8.0.0

    • Bump PostCSS to 7.0
    • Drop Node 4 support
  • 7.0.1

    • Drop dependency on gulp-util
  • 7.0.0

    • Bump PostCSS to 6.0
    • Smaller module size
    • Use eslint instead of jshint
  • 6.4.0

    • Add more details to PluginError object
  • 6.3.0

    • Integrated with postcss-load-config
    • Added a callback to configure postcss on per-file-basis
    • Dropped node 0.10 support
  • 6.2.0

    • Fix syntax error message for PostCSS 5.2 compatibility
  • 6.1.1

    • Fixed the error output
  • 6.1.0

    • Support for null files
    • Updated dependencies
  • 6.0.1

    • Added an example and a test to pass options to PostCSS (e.g. syntax option)
    • Updated vinyl-sourcemaps-apply to 0.2.0
  • 6.0.0

    • Updated PostCSS to version 5.0.0
  • 5.1.10

    • Use autoprefixer in README
  • 5.1.9

    • Prevent unhandled exception of the following pipes from being suppressed by Promise
  • 5.1.8

    • Prevent stream’s unhandled exception from being suppressed by Promise
  • 5.1.7

    • Updated direct dependencies
  • 5.1.6

    • Updated CssSyntaxError check
  • 5.1.4

    • Simplified error handling
    • Simplified postcss execution with object plugins
  • 5.1.3 Updated travis banner

  • 5.1.2 Transferred repo into postcss org on github

  • 5.1.1

    • Allow override of to option
  • 5.1.0 PostCSS Runner Guidelines

    • Set from and to processing options
    • Don’t output js stack trace for CssSyntaxError
    • Display result.warnings() content
  • 5.0.1

    • Fix to support object plugins
  • 5.0.0

    • Use async API
  • 4.0.3

    • Fixed bug with relative source map
  • 4.0.2

    • Made PostCSS a simple dependency, because peer dependency is deprecated
  • 4.0.1

    • Made PostCSS 4.x a peer dependency
  • 4.0.0

    • Updated PostCSS to 4.0
  • 3.0.0

    • Updated PostCSS to 3.0 and fixed tests
  • 2.0.1

    • Added Changelog
    • Added example for a custom processor in README
  • 2.0.0

    • Disable source map by default
    • Test source map
    • Added Travis support
    • Use autoprefixer-core in README
  • 1.0.2

    • Improved README
  • 1.0.1

    • Don’t add source map comment if used with gulp-sourcemaps
  • 1.0.0

    • Initial release

gulp-postcss’s People

gulp-postcss’s Issues

TypeError: Cannot read property ‘on’ of undefined

I’m getting the error below when I include the postcss pipe.
Not sure what’s wrong.

TypeError: Cannot read property 'on' of undefined
at DestroyableTransform.Readable.pipe (/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:535:7)
at Gulp.<anonymous> (/gulpfile.js:9:10)
at module.exports (/node_modules/orchestrator/lib/runTask.js:34:7)
at Gulp.Orchestrator._runTask (/node_modules/orchestrator/index.js:273:3)
at Gulp.Orchestrator._runStep (/node_modules/orchestrator/index.js:214:10)
at Gulp.Orchestrator.start (/node_modules/orchestrator/index.js:134:8)
at /usr/local/lib/node_modules/gulp/bin/gulp.js:129:20
at _combinedTickCallback (node.js:370:9)
at process._tickCallback (node.js:401:11)
at Function.Module.runMain (module.js:449:11)

Heres the Gulpfile.js

var gulp = require('gulp'),
    sass = require('gulp-sass'),
    postcss = require('gulp-postcss'),
    autoprefixer = require('autoprefixer');

gulp.task('css', function () {
    return gulp.src('sass/style.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(postcss[autoprefixer({browsers: ['last 2 versions']})])
        .pipe(gulp.dest(''));
});

Cannot Install Under Windows 10

Trying to install gulp-postcss for a project and it will not install. I get a series of errors about compiling about msbuild.exe and then it dumps.

Here is the full log of what NPM is doing:

[email protected] preinstall D:WordPressthemesjldc_scratchnode_modules.staginggmsmith-20f74d87
gm -version || convert -version

[email protected] install D:WordPressthemesjldc_scratchnode_modulescanvas
node-gyp rebuild

D:WordPressthemesjldc_scratchnode_modulescanvas>if not defined npm_config_node_gyp (node «C:Program Filesnodejsnode_modulesnpmbinnode-gyp-bin….node_modulesnode-gypbinnode-gyp.js» rebuild ) else (node rebuild )
Warning: Missing input files:
C:GTKbinzlib1.dll
C:GTKbinlibexpat-1.dll
C:GTKbinlibpng14-14.dll
C:GTKbinlibcairo-2.dll
C:GTKbinlibfontconfig-1.dll
C:GTKbinlibfreetype-6.dll
Building the projects in this solution one at a time. To enable parallel build, please add the «/m» switch.
Canvas.cc
CanvasGradient.cc
CanvasPattern.cc
CanvasRenderingContext2d.cc
color.cc
Image.cc
ImageData.cc
init.cc
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): warning C4005: ‘snprintf’: macro redefinition (compiling source file ..srcImage.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): note: command-line arguments: see previous definition of ‘snprintf’ (compiling source file ..srcImage.cc)
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1927): fatal error C1189: #error: Macro definition of snprintf conflicts with Standard Library function declaration (compiling source file ..srcImage.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): warning C4005: ‘snprintf’: macro redefinition (compiling source file ..srcCanvas.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): note: command-line arguments: see previous definition of ‘snprintf’ (compiling source file ..srcCanvas.cc)
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1927): fatal error C1189: #error: Macro definition of snprintf conflicts with Standard Library function declaration (compiling source file ..srcCanvas.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
PixelArray.cc
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): warning C4005: ‘snprintf’: macro redefinition (compiling source file ..srcCanvasPattern.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): note: command-line arguments: see previous definition of ‘snprintf’ (compiling source file ..srcCanvasPattern.cc)
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1927): fatal error C1189: #error: Macro definition of snprintf conflicts with Standard Library function declaration (compiling source file ..srcCanvasPattern.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): warning C4005: ‘snprintf’: macro redefinition (compiling source file ..srcCanvasGradient.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): note: command-line arguments: see previous definition of ‘snprintf’ (compiling source file ..srcCanvasGradient.cc)
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1927): fatal error C1189: #error: Macro definition of snprintf conflicts with Standard Library function declaration (compiling source file ..srcCanvasGradient.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): warning C4005: ‘snprintf’: macro redefinition (compiling source file ..srccolor.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): note: command-line arguments: see previous definition of ‘snprintf’ (compiling source file ..srccolor.cc)
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1927): fatal error C1189: #error: Macro definition of snprintf conflicts with Standard Library function declaration (compiling source file ..srccolor.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): warning C4005: ‘snprintf’: macro redefinition (compiling source file ..srcImageData.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): note: command-line arguments: see previous definition of ‘snprintf’ (compiling source file ..srcImageData.cc)
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1927): fatal error C1189: #error: Macro definition of snprintf conflicts with Standard Library function declaration (compiling source file ..srcImageData.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): warning C4005: ‘snprintf’: macro redefinition (compiling source file ..srcinit.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): note: command-line arguments: see previous definition of ‘snprintf’ (compiling source file ..srcinit.cc)
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1927): fatal error C1189: #error: Macro definition of snprintf conflicts with Standard Library function declaration (compiling source file ..srcinit.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): warning C4005: ‘snprintf’: macro redefinition (compiling source file ..srcPixelArray.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): note: command-line arguments: see previous definition of ‘snprintf’ (compiling source file ..srcPixelArray.cc)
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1927): fatal error C1189: #error: Macro definition of snprintf conflicts with Standard Library function declaration (compiling source file ..srcPixelArray.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): warning C4005: ‘snprintf’: macro redefinition (compiling source file ..srcCanvasRenderingContext2d.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1925): note: command-line arguments: see previous definition of ‘snprintf’ (compiling source file ..srcCanvasRenderingContext2d.cc)
C:Program Files (x86)Windows Kits10Include10.0.10150.0ucrtstdio.h(1927): fatal error C1189: #error: Macro definition of snprintf conflicts with Standard Library function declaration (compiling source file ..srcCanvasRenderingContext2d.cc) [D:WordPressthemesjldc_scratchnode_modulescanvasbuildcanvas.vcxproj]

‘gm’ is not recognized as an internal or external command,
operable program or batch file.
Invalid drive specification.
npm WARN install:[email protected] [email protected] preinstall: gm -version || convert -version
npm WARN install:[email protected] Exit status 4
gyp ERR! build error
gyp ERR! stack Error: C:Program Files (x86)MSBuild14.0binmsbuild.exe failed with exit code: 1
gyp ERR! stack at ChildProcess.onExit (C:Program Filesnodejsnode_modulesnpmnode_modulesnode-gyplibbuild.js:276:23)
gyp ERR! stack at emitTwo (events.js:87:13)
gyp ERR! stack at ChildProcess.emit (events.js:172:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Windows_NT 10.0.10586
gyp ERR! command «C:Program Filesnodejsnode.exe» «C:Program Filesnodejsnode_modulesnpmnode_modulesnode-gypbinnode-gyp.js» «rebuild»
gyp ERR! cwd D:WordPressthemesjldc_scratchnode_modulescanvas
gyp ERR! node -v v4.2.1
gyp ERR! node-gyp -v v3.2.1
gyp ERR! not ok
npm WARN install:[email protected] [email protected] install: node-gyp rebuild
npm WARN install:[email protected] Exit status 1
npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: [email protected]

Depracated dependencies info appearing during the first scss->css compile while using gulp

It appears only at the very first compile which takes the longest.
I noticed that the log appears for every single postcss plugin I use (lostgrid and autoprefixer in my example), I use the latest release of gulp-postcss.

Container#eachAtRule is deprecated. Use Container#walkAtRules instead.
Container#eachDecl is deprecated. Use Container#walkDecls instead.
Node#removeSelf is deprecated. Use Node#remove.
Container#eachRule is deprecated. Use Container#walkRules instead.
Node#style() is deprecated. Use Node#raw()
Node#before is deprecated. Use Node#raws.before
Node#_value was deprecated. Use Node#raws.value

gulp-postcss silently catch all errors in other pipes

Support runner guidelines

syntax: scss can’t work

this’s my gulp task

gulp.task('css', function() {
  var processors = [cssImport(),customProperties(),alias,crip()];
   return gulp.src(sourceDir + '/postcss/*.pcss')
    .pipe(postcss(processors, {syntax : scss}))
   .pipe(rename({
     suffix: '-postcss',
     extname: '.css'
    }))`
    .pipe(gulp.dest(targetDir + '/css'));
});

this’s my postcss file

//这是一个测试
body{
  color: red;
}

when I complete the task, the inline-comment still exists

//这是一个测试

body{
  color: red;
}```

Clean up error hangling

Getting ‘Unknown word’ font import

I get the following error:

Error: postcss-import-url: <css input>:1:1: Unknown word

when the following import is included in my source:

@import url("//hello.myfonts.net/count/3022f1");

Any advise to get round this error?

browsers: [‘not Chrome’] throws an error

I get an error when I want to target all browsers. The browser query I am using is as followed:

BrowserslistError: Unknown browser query Chrome

I solved it already by changing the query to [‘last 99 versions’] but I thought is was worth mentioning either way :)

TypeError in plugin ‘gulp-postcss’ Message: Cannot read property ‘before’ of undefined

Still getting this error when using @import with latest versions of gulp-postcss and cssnext.

I was under the impression postcss-import and most plugins were up to speed with the new version now? Just going round in circles on github trying to work out where the problem lies. But as the error is thrown as gulp-postcss plugin. I’m raising the issue here.

Thanks in advance

error

events.js:72
        throw er; // Unhandled 'error' event
              ^
ReferenceError: Promise is not defined
    at LazyResult.async (D:_hostflteinvestrootnode_modulesgulp-postcssnode_modulespostcssliblazy-result.js:93:31)
    at LazyResult.then (D:_hostflteinvestrootnode_modulesgulp-postcssnode_modulespostcssliblazy-result.js:56:21)
    at Transform.stream._transform (D:_hostflteinvestrootnode_modulesgulp-postcssindex.js:44:10)
    at Transform._read (_stream_transform.js:179:10)
    at Transform._write (_stream_transform.js:167:12)
    at doWrite (_stream_writable.js:226:10)
    at writeOrBuffer (_stream_writable.js:216:5)
    at Transform.Writable.write (_stream_writable.js:183:11)
    at write (D:_hostflteinvestrootnode_modulesgulpnode_modulesvinyl-fsnode_modulesthrough2node_modulesreadable-streamlib_stream_readabl
e.js:623:24)
    at flow (D:_hostflteinvestrootnode_modulesgulpnode_modulesvinyl-fsnode_modulesthrough2node_modulesreadable-streamlib_stream_readable
.js:632:7)

update vinyl-sourcemaps-apply

In vinyl-sourcemaps-apply 0.2.0 was updated source-map module

gulp-postcss returns too early

gulp-postcss returns too early when using asynchronous plugins. Reproducible with the following code:

gulpfile.js

var postcss = require('gulp-postcss');
var gulp = require('gulp');

gulp.task('css', function () {
    gulp.src('app.css')
            .pipe( postcss([require('./test.js')]) )
            .pipe( gulp.dest('build/') )
});

test.js

var postcss = require('postcss');

module.exports = postcss.plugin('test', function () {
    return function (css) {
        return new Promise(function (resolve) {
            setTimeout(resolve, 10000);
        });
    };
});
>gulp css
[16:22:06] Using gulpfile ~DocumentsGitHubtestgulpfile.js
[16:22:06] Starting 'css'...
[16:22:06] Finished 'css' after 40 ms <--- finishes after 40 ms rather than the expected 10 seconds
*process waits for 10 more seconds* 
>

TypeError: undefined is not a function

I get the error:
TypeError: undefined is not a function
Whenever I try using cssnext. I’m not sure if this is an issue with gulp-postcss or with cssnext, but the log leads me to believe it is a problem with gulp-postcss.

This is my gulpfile:

var gulp = require("gulp");
var postcss = require("gulp-postcss");
var cssnext = require("cssnext");

gulp.task("css", function () {
  var processors = [
    cssnext()
  ];

  return gulp.src("main.css")
    .pipe(postcss(processors))
    .pipe(gulp.dest("css/"));
});

And this is the output of running gulp css:

[14:06:27] Using gulpfile ~/Desktop/postcss-test/gulpfile.js
[14:06:27] Starting 'css'...

events.js:85
      throw er; // Unhandled 'error' event
            ^
TypeError: undefined is not a function
at LazyResult.run (/Users/Christian/Desktop/postcss-test/node_modules/gulp-postcss/node_modules/postcss/lib/lazy-result.js:193:24)
at /Users/Christian/Desktop/postcss-test/node_modules/gulp-postcss/node_modules/postcss/lib/lazy-result.js:107:37
at LazyResult.asyncTick (/Users/Christian/Desktop/postcss-test/node_modules/gulp-postcss/node_modules/postcss/lib/lazy-result.js:120:15)
at /Users/Christian/Desktop/postcss-test/node_modules/gulp-postcss/node_modules/postcss/lib/lazy-result.js:118:27
at LazyResult.asyncTick (/Users/Christian/Desktop/postcss-test/node_modules/gulp-postcss/node_modules/postcss/lib/lazy-result.js:120:15)
at /Users/Christian/Desktop/postcss-test/node_modules/gulp-postcss/node_modules/postcss/lib/lazy-result.js:118:27
at LazyResult.asyncTick (/Users/Christian/Desktop/postcss-test/node_modules/gulp-postcss/node_modules/postcss/lib/lazy-result.js:120:15)
at /Users/Christian/Desktop/postcss-test/node_modules/gulp-postcss/node_modules/postcss/lib/lazy-result.js:118:27
at LazyResult.asyncTick (/Users/Christian/Desktop/postcss-test/node_modules/gulp-postcss/node_modules/postcss/lib/lazy-result.js:120:15)
at /Users/Christian/Desktop/postcss-test/node_modules/gulp-postcss/node_modules/postcss/lib/lazy-result.js:118:27

Use PostCSS 3.0

New PostCSS is 6 times faster. Changelog

Please upgrade to PostCSS 4.0

Simplify postcss execution

Postcss now accepts Processor instance in postcss() constructor too, so we can get rid of processors.forEach(processor.use.bind(processor)).

Error: Cannot find module ‘autoprefixer-core’

I followed the instructions in your readme and it ends up with this error message:

Error: Cannot find module 'autoprefixer-core'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/verpixelt/projects/gulp-boilerplate/gulpfile.js:26:20)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)

.css:1:1: Unknown word

I am getting an Unknown word error for // comments

Error in plugin 'gulp-postcss'
Message:
postcss-import:style.css:1:1: Unknown word

// Comment
^ 

How to use postcss with @imports?

I have a problem when trying to use postcss ( from gulp ) for css files that has @imports.
Here is the gulp task

gulp.task('css', function () {

    var postcss = require('gulp-postcss');
    var postcssImport = require('postcss-import');
    var sourcemaps = require('gulp-sourcemaps');
    var autoprefixer = require('autoprefixer-core');

    return gulp.src('./src/css/app.css')
        .pipe(sourcemaps.init())
        .pipe(postcss([
            postcssImport(),
            autoprefixer({ browsers: ['last 2 versions'] })
        ]))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('./dist/css'));
});

and two simple css files:
common.css

html,
body {
    margin: 0;
    padding: 0;
}

app.css

[18:06:55] Starting 'css'...
Container#eachAtRule is deprecated. Use Container#walkAtRules instead.
Node#before is deprecated. Use Node#raws.before
Container#eachRule is deprecated. Use Container#walkRules instead.
Container#eachDecl is deprecated. Use Container#walkDecls instead.

events.js:85
      throw er; // Unhandled 'error' event
            ^
TypeError: Cannot read property 'before' of undefined
    at Stringifier.raw (...node_modulesgulp-postcssnode_modulespostcsslibstringifier.js:121:30)
    at Stringifier.body (...node_modulesgulp-postcssnode_modulespostcsslibstringifier.js:93:31)
    at Stringifier.root (...node_modulesgulp-postcssnode_modulespostcsslibstringifier.js:37:14)
    at Stringifier.stringify (...node_modulesgulp-postcssnode_modulespostcsslibstringifier.js:33:24)
    at _default.stringify (...node_modulesgulp-postcssnode_modulespostcsslibstringify.js:14:9)
    at _default.generateString (...node_modulesgulp-postcssnode_modulespostcsslibmap-generator.js:231:14)
    at _default.generateMap (...node_modulesgulp-postcssnode_modulespostcsslibmap-generator.js:189:14)
    at _default.generate (...node_modulesgulp-postcssnode_modulespostcsslibmap-generator.js:271:25)
    at LazyResult.stringify (...node_modulesgulp-postcssnode_modulespostcssliblazy-result.js:221:24)
    at ...node_modulesgulp-postcssnode_modulespostcssliblazy-result.js:158:27

Problem with Node v4.0.0 after upgrading to gulp-postcss 6.0.0

Hi,

I recently installed Node v4.0.0 on my system, then after upgrading gulp-postcss to 6.0.0 the process exits with this error message:

Your current PostCSS version is 5.0.4, but postcss-custom-media uses 4.1.16. Perhaps this is the source of the error below.

Any idea what might be causing the problem? Thanks!

A way to configure gulp-postcss not to fail a build on css syntax error

Is there a way to configure PostCSS plugin to just log the error and not fail a build when it encounters a css syntax error? It may be useful in some live-reloading workflows. For instance when I use gulp with browser-sync’s watch plugin that lints code on every change the failed build also fails watching process so I have to restart it every time.

As a possible solution gulp-poctcss may have a switch to handle all postcss errors, log them to console and proceed:

gulp.src(cssFile)
    .pipe(postcss([...], {failOnError: false}))

error setting from and to options

Hi!!

I think that

opts.from = opts.to = file.path

Is not ok.. opts.to must be the path of the «gulp.dest» . What do you think?

Unable to use cssnext as a processor with gulp-postcss

I’d like to use the cssnext plugin pack with gulp-postcss, as my first processor to be followed by a set of other cherry picked postcss plugins. The trouble is that I can’t figure out how to get cssnext working with gulp-postcss. In the following code snippet I think I’m using cssnext() wrong within the processors array, but everything I’ve tried to correct it fails.

var gulp = require('gulp');
var postcss = require('gulp-postcss');
var cssnext = require('cssnext');

config = {
  cssDistPath: './dist/css',
  cssSrcGlob:  './src/css/**/*.css'
};

gulp.task('css', function () {

  var processors = [
    cssnext({
      features: {
        calc: {
            preserve: true
        }
      }
    })
  ];

  return gulp.src(config.cssSrcGlob)
    .pipe(postcss(processors))
    .pipe(gulp.dest(config.cssDistPath));

});

Do you have any suggestions on how to get this working, or a better configuration?

Use postcss-runner keyword

In latest Guidelines discussion we decide to use postcss-runner instead of postcssrunner.

Gulp crash

On syntax error like

// Unhandled stream error in pipe.
CssSyntaxError: path.css:15:1: Unclosed block

Have to use gulp-plumber for this.

Can you do some improvements to fix this?

Cannot read property…

Hi,

i’m using gulp-postcss together with gulp-sass 1.2.4, autoprefixer-core 4.0.2, css-mqpacker 2.0.0 and csswring 2.0.0 like this:

gulp.task('build:css', function() {
    return gulp
        .src(config.paths.assetsDev + '/scss/main.scss')
        .pipe(g.sourcemaps.init())
        .pipe(g.sass())
        .pipe(g.postcss([
                autoprefixer(config.autoprefixer),
                mqpacker,
                csswring(config.csswring)
        ]))
        .pipe(g.sourcemaps.write('.', {
            includeContent: true,
            sourceRoot: '.'
        }))
        .pipe(gulp.dest(path.join(config.paths.assets, 'css')));
});

When using gulp-postcss 4.0.0 i get the following error:

TypeError: Cannot read property '_autoprefixerDisabled' of undefined at Processor.disabled (.../node_modules/autoprefixer-core/lib/processor.js:133:15)

Or if i disable autoprefixer and only use mqpacker and csswring, i get:

TypeError: Cannot read property 'length' of undefined at wringRule (.../node_modules/csswring/lib/csswring.js:375:18)

I had no problems with that when using gulp-postcss 3.0.0 and switching back «solves» the problem.

Although i’m using a lot of other modules, i assume this is a gulp-postcss problem…?!

Greetings,

Simbo

Incorrect source map when «to» option passed

I’m using gulp-sass, gulp-postcss and gulp-sourcemaps in my project.
When I set to option in the postcss(), the source map content is incorrect.

gulp.src('app/styles/*.scss')
  .pipe($.sourcemaps.init({loadMaps: true}))
  .pipe($.sass().on('error', $.sass.logError))
  .pipe($.postcss(processors, {to: '.tmp/styles/main.css'}))
  .pipe($.sourcemaps.write('.'))
  .pipe(gulp.dest('.tmp/styles'))

postcss-sourcemaps

Without to option, I could get proper source map, but some postcss plugins need this option.
Am I overlooking something, or is this bug?

I created simple gulp tasks to reproduce this issue. I hope this helps.
https://github.com/htanjo/postcss-sourcemaps-test

problem in a package using postcss: promisse is not defined

output of my terminal:

/var/www/vecchio/node_modules/gulp-autoprefixer/node_modules/postcss/lib/lazy-result.js:152
this.processing = new Promise(function (resolve, reject) {
^
ReferenceError: Promise is not defined

ChangeLog

I think ChangeLog is very important for every project, beacuse commits list contain a lot of unnecessary information.

Add syntax options to docs

Impossible to force «disable sourcemaps»

It is impossible to tell postcss to forcibly disable sourcemap support:

var ieFilter = gulpFilter(['main.css'], {restore: true});

gulp.src('**/*.css')
    .pipe(sourcemaps.init())
    .pipe(postcss([autoprefixer]))
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest(paths.staticBasePath))
    .pipe(ieFilter)
    .pipe(postcss([postcssIE8], {map: false}))
    .pipe(rename({extname: '-ie.css'}))
    .pipe(gulp.dest(paths.staticBasePath));

This throws an error. I am not quite sure if this is a problem of gulp-sourcemaps or gulp-postcss. But when I change the map-generation in gulp-postcss/index.js it works correctly:

if (file.sourceMap && (!options || options.map !== false)) {

Providing array, but getting `Please provide array of postcss processors!`

I’ve got the following linter setup for my sass, and i’m getting an error asking me to provide an array of postcss processors — even though i am supplying an array.

I’m using gulp-postcss for postcss and node 0.10 —harmony. Apparently this is a gulp-postcss issue rather than a postcss issue (postcss/postcss#639)

gulp.task("sass-lint", function() {

  var stylelintConfig = {
    "rules": {
      "block-no-empty": 2,
      "color-no-invalid-hex": 2,
      "declaration-colon-space-after": [2, "always"],
      "declaration-colon-space-before": [2, "never"],
      "function-comma-space-after": [2, "always"],
      "function-url-quotes": [2, "double"],
      "media-feature-colon-space-after": [2, "always"],
      "media-feature-colon-space-before": [2, "never"],
      "media-feature-name-no-vendor-prefix": 2,
      "no-multiple-empty-lines": 2,
      "number-leading-zero": [2, "never"],
      "number-no-trailing-zeros": 2,
      "property-no-vendor-prefix": 2,
      "rule-no-duplicate-properties": 2,
      "rule-no-single-line": 2,
      "rule-trailing-semicolon": [2, "always"],
      "selector-list-comma-newline-after": [2, "always-multi-line"],
      "selector-no-id": 2,
      "string-quotes": [2, "double"],
      "value-no-vendor-prefix": 2
    }
  };

  var processors = [
    stylelint(stylelintConfig),
    reporter({
      clearMessages: true,
    })
  ];

  return gulp.src(config.sourceFiles.styles)
    .pipe(postcss(processors, {syntax: scss}));

});

Cannot parse .pcss file

In my project both the preprocessed file and processed file live in the same location so I need to give each of them a different file extension. However gulp will not recognise .pcss or .postcss.

For example I have the following:

gulp.task('css', function () {
    var postcss    = require('gulp-postcss');
    var sourcemaps = require('gulp-sourcemaps');
    var rename = require('gulp-rename');

    return gulp.src('src/**/*.pcss', {base: './'})
        .pipe( sourcemaps.init() )
        .pipe( postcss([ require('autoprefixer'), require('precss') ]) )
        .pipe( sourcemaps.write('.') )
        .pipe( rename({extname: '.css'}) )
        .pipe( gulp.dest('./') );
});

Any idea why this could be?

Log messages

There doesn’t appear to be anyway to get access to result.messages as result isn’t exposed anywhere.

This makes integrating tools like cssstats difficult because it just pushes to messages

postcss().use(cssstats()).process(css).then(function (result) {
  result.messages.forEach(function (message) {
    console.log(message)
  })
})

Am I missing something or is this just not possible now?

Cannot make sourcemaps work

Hi everyone. I am fighting to get sourcemaps working with gulp-postcss plugin but I’ve run out of ideas, and don’t know how to fix it. My sass task looks like this:

gulp.task('sass:dev', function() {
    gulp.src('app/styles/**/*.scss)
        .pipe($.sourcemaps.init())
        .pipe($.sass(config.sass).on('error', $.sass.logError))
        .pipe($.postcss([
            autoprefixer({
                browsers: ['last 2 versions']
            })
        ]))
        .pipe($.sourcemaps.write('.'))
        .pipe(gulp.dest('.tmp/assets/styles'))
        .pipe(reload({ stream: true }));
});

Above config generates app.css.map file in destination directory as it should but sourcemaps does not works in browser. Here you can see that source map file (broken): https://gist.github.com/sqal/f894149870da902707f8 However If i remove postcss from my task, everything works as it should: https://gist.github.com/sqal/d3328b6c283ddbfee88f
Is there some bug in postcss or am I missing something here? Any hints on why it is not working for me would be greatly appreciated :) Thanks.

// Forgot to mention. I am using gulp-postcss 5.1.6, gulp-sourcemaps 1.5.2 and autoprefixer-core 5.1.11

How about exemplifying error handling in the Readme?

The confusion in #32 is legitimate, I think, given that users would expect runners to show errors without additional configuration. Since it looks like the solution is the use gulp-plumber or .on('error', ..), maybe it would reduce confusion to exemplify this in the Readme and point out its importance. What do you think?

How to split a css file into multiple

I have been digging for hours trying to find an example of a plugin that can output two files from a single source. I am at a loss and I am hoping I am simply overlooking something obvious.

It appears as though right now there is a hard assumption that 1:1 for from-file:to-file where as I am hoping to find a way to do 1:n+1. Any help would be greatly appreciated!

Undesired inline source maps are outputted when not using gulp-sourcemaps.

When not using gulp-sourcemaps (I’m not using it right now since gulp-postcss and gulp-autoprefixer are currently broken) gulp-postcss outputs an inline source map that was not requested.

Fails silently with missing file and postcss-import

It should throw an error: postcss/postcss-import#35 (comment)

But when using gulp-postcss w/ postcss-import and you try to import a missing file, the gulp task never finishes and postcss processing seems to abort.

Process inline CSS in HTML using PostCSS

It would be great if gulp-postcss could process CSS within HTML files too, for the reasons mentioned in postcss/postcss#596.

Do you think this could be implemented?

Looking forward to hear your thoughts!

Cheers :)

Sourcemap generation is very slow

I have sass generate sourcemaps and I use this plugin to apply autoprefixer and it slows down the sourcemap generation a lot. Is there a way to speed it up? Time difference is huge few seconds vs few mins. I have confirmed this by commenting out this task.

Possible reason for slow down could be appending source code in the sourcemap.

problem with package.json

Sourcemaps doesn’t work

I compile css with this

    return gulp.src(bower(['**/*.css']).concat([
            'src/css/plugins/[^_]*.css',
            'src/css/globals/[^_]*.css',
            'src/css/shared/[^_]*.css',
            'src/css/components/[^_]*.css',
            'src/css/sections/[^_]*.css'
        ]))
        .pipe($.sourcemaps.init())
        .pipe($.concat('bundle.css'))
        .pipe($.plumber())
        .pipe($.postcss([
            require('autoprefixer-core')()
        ]))
        .pipe(gulp.dest('dist/assets/css'))
        .pipe($.rename({suffix: '.min'}))
        .pipe($.plumber())
        .pipe($.postcss([
            require('csswring')({
                removeAllComments: true
            })
        ]))
        .pipe($.sourcemaps.write('.'))
        .pipe(gulp.dest('dist/assets/css'));

And chrome gave me bundle.css in sources with bundle.min.css name.
When I commented both postcss pipes, it worked.

Add Sass encoding note

Update to PostCSS 5.0.0

Tomorrow many plugin for 5.0 API will be released, so we need to update runners.

/cc @w0rm

Add support for async postcss processors

Tag releases

Please tag the releases which have been pushed to npm, in order to make it easier to see what are the differences between each release.
Tagging could be done for example:

git tag v5.1.1 1245750bfcd800b6d913224b2ccfa51725da63aa

Add Promise polyfill

So, how does one integrate gulp-ruby-sass into this flow?

Can you please provide an example? I have tried, yet failed every time.

В последнем уроке мы рассказали, как вы можете начать работу с PostCSS мгновенно, используя CodePen или Prepros. Эти параметры хороши, но ограничены тем, что вы не можете контролировать, какие плагины доступны для использования.

В этом уроке мы рассмотрим, как вы можете использовать PostCSS с исполнителем задач Gulp , что позволит вам самим решить, какие плагины вы хотите использовать, и, следовательно, действительно подключиться к экосистеме плагинов.

Примечание . Если вы никогда раньше не работали с командной строкой или исполнителями задач, я рекомендую перед началом этого урока ознакомиться с нашей бесплатной серией: Командная строка для веб-дизайна .

Предпосылки

Учитывая, что мы будем работать с Gulp, мы предполагаем, что у вас уже есть необходимые условия для его использования:

  • Node.js
  • NPM
  • Гит

Если вы не уверены, что они установлены, следуйте учебному пособию «Командная строка для веб-дизайна: укрощение сторонних пакетов», которое поможет вам выполнить эти предварительные условия.

Также убедитесь, что вы понимаете основы использования Gulp, следуя руководству «Командная строка для веб-дизайна: автоматизация с Gulp» . Кроме того, следуйте инструкциям в разделе «Настройка проекта для Gulp» руководства. Прежде чем двигаться дальше, у вас должна быть папка проекта с:

  • «Gulpfile.js» (Gulpfile)
  • Файл «package.json»
  • Gulp установлен в папке «node_modules» и установлен как dev-зависимость для вашего проекта

Базовая настройка Gulp PostCSS

Внутри вашей папки проекта создайте две подпапки, одну с именем «src» и одну с именем «dest». В папке «src» будут храниться ваши необработанные CSS-файлы, а в папке «dest» будут записаны обработанные вами файлы PostCSS.

Следующее, что вам нужно сделать, это установить плагин gulp-postcss в ваш проект – мы будем использовать это для обработки нашей обработки PostCSS.

В терминале / командной строке, указанной в папке вашего проекта, выполните команду:

1

npm install –save-dev gulp-postcss

После завершения установки структура вашего проекта должна выглядеть следующим образом:

Теперь откройте ваш Gulpfile для редактирования и создайте переменные для вызова в модулях «gulp» и «gulp-postcss», добавив следующий код:

1

2

var gulp = require(‘gulp’);

var postcss = require(‘gulp-postcss’);

Теперь мы можем настроить задачу для чтения исходного файла CSS и обработки его через PostCSS.

Добавьте следующее:

1

2

3

4

5

6

7

gulp.task(‘css’, function () {

  var processors = [

  ];

  return gulp.src(‘./src/*.css’)

    .pipe(postcss(processors))

    .pipe(gulp.dest(‘./dest’));

});

Давайте разберем то, что мы имеем в коде выше.

В первой строке мы настроили задачу css именем css . Эта задача выполняет функцию, и внутри этой функции мы создали массив с именем processors . Прямо сейчас этот массив пуст, но через мгновение мы заполним его плагинами PostCSS, которые мы хотим использовать.

После массива processors мы указали файлы, которые мы хотим использовать для обработки: любые CSS-файлы в папке «src».

В первой из двух строк, использующих функцию pipe() , мы настраиваем выполнение PostCSS с помощью функции postcss() . В качестве аргумента через эту функцию мы передаем наш массив processors , который позже сообщит PostCSS, какие плагины мы хотим использовать.

Наконец, со второй из двух функций pipe() мы получили наш обработанный код, записанный в новый файл CSS в нашей папке dest.

Запустите тестовую компиляцию

Создайте новый файл «style.css» в папке «src» и добавьте в него несколько тестовых CSS, таких как:

1

2

3

.test {

    background: black;

}

Теперь в вашем терминале / командной строке, все еще указав на папку вашего проекта, выполните команду:

Это запустит задачу, которую вы только что настроили, и в результате вы должны найти новый файл «style.css» внутри вашей папки «dest».

Когда вы откроете этот новый файл, вы увидите код, идентичный коду вашего исходного файла. Код не изменился, потому что мы еще не использовали какие-либо плагины PostCSS, и, как вы узнаете из предыдущего урока, именно плагины выполняют фактические манипуляции с CSS.

Добавить PostCSS плагины

Теперь мы добавим выбор плагинов и пакетов PostCSS: Autoprefixer (добавляет префиксы вендора), cssnext (включает синтаксис в будущем) и precss (расширяется функциональностью, подобной Sass).

Выполните следующие команды, чтобы установить каждый плагин в свой проект:

1

2

3

npm install autoprefixer –save-dev

npm install cssnext –save-dev

npm install precss –save-dev

Примечание . Установка cssnext и precss может занять некоторое время, поскольку они представляют собой пакеты из нескольких плагинов.

Далее мы определим переменные для загрузки каждой из них в наш проект. Добавьте следующий код под двумя существующими переменными в верхней части вашего Gulpfile:

1

2

3

var autoprefixer = require(‘autoprefixer’);

var cssnext = require(‘cssnext’);

var precss = require(‘precss’);

Затем мы добавим эти три плагина в массив processors в нашей задаче gulp. Обновите массив до следующего:

1

2

3

4

5

var processors = [

   autoprefixer,

   cssnext,

   precss

 ];

После добавления трех плагинов в наш массив процессоров PostCSS будет знать, что мы хотим применить каждый из них к нашему исходному CSS.

Теперь мы готовы добавить тестовый код в наш файл «src / style.css» и проверить, что все работает. Удалите то, что у вас уже есть в файле, и вместо этого добавьте этот CSS:

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

/* Testing autoprefixer */

.autoprefixer {

  display: flex;

}

/* Testing cssnext */

.cssnext {

  background: color(red alpha(-10%));

}

/* Testing precss */

.precss {

  @if 3 < 5 {

    background: green;

  }

  @else {

    background: blue;

  }

}

Теперь снова введите команду gulp css , и полученный файл в папке «dest» должен иметь следующее содержимое:

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

/* Testing autoprefixer */

.autoprefixer {

  display: -webkit-box;

  display: -webkit-flex;

  display: -ms-flexbox;

  display: flex;

}

/* Testing cssnext */

.cssnext {

  background: rgba(255, 0, 0, 0.9);

}

/* Testing precss */

.precss {

  background: green

}

Как указано выше, вы должны увидеть, что префиксы вендоров были добавлены в первый класс Autoprefixer, цвет rgba() был выведен cssnext во второй класс, а @if @else была оценена PreCSS в третьем учебный класс.

Настройка параметров плагина

Примечание : если вы хотите настроить параметры для плагина, добавьте пару скобок после его имени в массиве препроцессоров и передайте параметры там. Например, вы можете указать список браузеров, с которым вы хотите работать Autoprefixer, например:

1

2

3

4

5

var processors = [

   autoprefixer({browsers: [‘last 1 version’]}),

   cssnext,

   precss

 ];

Поделиться своим проектом

Прелесть PostCSS в том, что он может быть настроен на любую комбинацию плагинов. Однако перед нами стоит задача обеспечить, чтобы другие люди, желающие работать над проектом, имели одинаковую настройку плагинов PostCSS. Благодаря npm эта проблема решается через систему управления зависимостями.

Поскольку вы используете флаг --save-dev каждый раз, когда устанавливаете плагин в свой проект, он будет добавлен в ваш файл «project.json» как зависимость dev. Это означает, что если вы хотите поделиться своим проектом с другими, они могут запустить команду npm install для пакета, которым вы делитесь с ними, и автоматически установить все те же плагины.

Чтобы узнать больше о том, как управление зависимостями работает с NPM, ознакомьтесь с руководством «Командная строка для веб-дизайна: Укрощение сторонних пакетов» .

Давайте подведем итоги

Подводя итог вышесказанному:

  • Создайте проект npm с установленным Gulp и Gulpfile внутри
  • Установите плагин gulp-postcss
  • Настройте ваш Gulpfile для загрузки плагинов gulp и gulp-postcss
  • Создайте задание для компиляции вашего CSS
  • В рамках задачи настройте массив processors
  • postcss() исходный CSS через postcss() с массивом processors переданным в качестве аргумента

Оттуда вы можете выполнить те же самые важные шаги, чтобы включить любой плагин PostCSS в вашем проекте:

  • Установите плагин в свой проект с
    npm install <plugin_name> --save-dev
  • Определите переменную для загрузки плагина в вашем Gulpfile, например
    var autoprefixer = require('autoprefixer');
  • Добавьте это имя переменной в ваш массив preprocessors .

Проверьте репозиторий Github для начальных файлов и завершенных примеров.

Далее: Grunt + PostCSS

В следующем уроке мы расскажем, как настроить проект PostCSS в другом из двух основных исполнителей задач: Grunt. Увидимся там!

Понравилась статья? Поделить с друзьями:
  • Error in plots display expecting plot structure but received
  • Error in plot3d first argument must be either in standard or parametric form
  • Error in plot unexpected options
  • Error in plot unexpected option
  • Error in plot procedure expected as range contains no plotting variable