简体   繁体   中英

Set environment mode and output messages when starting a gulp task

I'm wondering how I can output messages to the terminal when I run a gulp process and how I can set an environment to run tasks in specific ways.

  1. I'm sure I've seen something like gulp scripts:dev before but don't know how to use, can anyone advice how I can do this?
  2. How would you run the default task this way, gulp deafult:dev ?
  3. Is it possible to ask the user which environment they want to run the task for in the terminal when the execute the gulp command, if they don't specify it.

I've used the gulp-if plugin to achieve this but it works slightly differently, you need to set a node environment variable before running gulp ie NODE_ENV=dev gulp .

var gulp = require('gulp'),
    sass = require('gulp-ruby-sass'),
    gulpif = require('gulp-if'),
    shell = require('gulp-shell');

var isDev = process.env.NODE_ENV === 'dev';

// gulp-shell task to output messages to terminal
gulp.task('info', shell.task([
    'echo run in developer mode with  this command: NODE_ENV=dev gulp'
]));

// Styles Task
// Uses gulp-if plugin to run task differently dependent on env.
gulp.task('styles', ['info'], function () { // eslint-disable-line strict
    return sass('css/sass/*.scss', {
        style: gulpif(!isDev,'compressed','expanded'),
        cacheLocation: 'css/sass/.sass-cache',
        sourcemap: isDev
    })
    [...code ommitted...]
});    

gulp.task('default', ['h','styles']);
  1. Also I've used gulp-shell above to output messages to the terminal, but it's pretty basic. Is there anyway I can do something similar with line breaks and colours with the message I output to the terminal.

Take a look at gulp-environments - you can set as many as you like but dev and prod are sufficient for most. You can define each in the gulpfile and set different events to occur from within each gulp script. So your styles script can contain a .pipe(dev(some dev only sourcemap code))and a .pipe(prod(some mini fixed build code)). You can run the script from git bash with an --env flag... gulp --env dev or gulp --env prod. And run two completely different build cycles from more or less the same script. You set your default gulp task to run all your page scripts and it will only execute the ones for each environment as it loops.

To output messages to the terminal you can require gulp-util node module.

Example code:

gulp.task('test', () => {
    gutil.log(gutil.colors.yellow('=== Testing ==='));    
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM