Skip to content Skip to sidebar Skip to footer

Using Variables In Gulp For The Destination File Name?

I am new to gulp and I am wondering if what I want to achieve is practical or possible. My projects structure: root | components | | | component_1 | | styles.scss | | a

Solution 1:

It wouldn't be too hard, depending on how much you need it to be dynamic. Gulp is pure JS, so you can very easily write your own functions. you can use the gulp-rename plugin to rename part or all of the file name before saving.

Here's a rough idea to get you started:

var rename = require('gulp-rename'),
    path = require('path'),
    glob = require('glob'); // npm i --save-dev glob    var components = glob.sync('components/*').map(function(componentDir) {
        return path.basename(componentDir);
    });

components.forEach(function(name) {
    gulp.task(name+'-style', function() {
        return gulp.src('components/'+name+'/styles.scss')
            .pipe(sass()) // etc
            .pipe(rename(name + '.css'))
            .pipe(gulp.dest('public/assets/css'))
    });

    gulp.task(name+'-js', function() {
        // similar idea for JS files
    });

    gulp.task(name+'-build', [name+'-style', name+'-js']);
});

// build all components
gulp.task('build-components', components.map(function(name){ return name+'-build'; }));

Now you'll have tasks named component_1-build, component_1-style, component_1-js, etc, for each component.

You also have a task that can build all components.

Solution 2:

Old question i know, but i been playing around in this area today, and hence came across this question. This may help someone if you are wanting to do something dynamic with the destination path.

You can supply a function as the argument to gulp.dest and hence do some pre processing on the destination path like this:

.pipe(gulp.dest(function (file) {
    // file is the current file in the stream// do something here               return pathString;
}));

Post a Comment for "Using Variables In Gulp For The Destination File Name?"