GithubHelp home page GithubHelp logo

gulp-changed's Introduction

gulp-changed

Only pass through changed files

No more wasting precious time on processing unchanged files.

By default it's only able to detect whether files in the stream changed. If you require something more advanced like knowing if imports/dependencies changed, create a custom comparator, or use another plugin.

Install

npm install --save-dev gulp-changed

Usage

import gulp from 'gulp';
import changed from 'gulp-changed';
import ngAnnotate from 'gulp-ng-annotate'; // Just as an example

const SOURCE = 'src/*.js';
const DESTINATION = 'dist';

exports.default = () => (
	gulp.src(SOURCE)
		.pipe(changed(DESTINATION))
		// `ngAnnotate` will only get the files that
		// changed since the last time it was run
		.pipe(ngAnnotate())
		.pipe(gulp.dest(DESTINATION))
);

API

changed(destination, options?)

destination

Type: string | Function

Destination directory. Same as you put into gulp.dest().

This is needed to be able to compare the current files with the destination files.

Can also be a function returning a destination directory path.

options

Type: object

cwd

Type: string
Default: process.cwd()

Working directory the folder is relative to.

extension

Type: string

Extension of the destination files.

Useful if it differs from the original, like in the example below:

export const jade = () => (
	gulp.src('src/**/*.jade')
		.pipe(changed('app', {extension: '.html'}))
		.pipe(jade())
		.pipe(gulp.dest('app'))
);
hasChanged

Type: Function
Default: compareLastModifiedTime

Function that determines whether the source file is different from the destination file.

Built-in comparators

Named imports:

  • compareLastModifiedTime
  • compareContents
Example
import {compareContents} from 'gulp-changed';

export const jade = () => (
	gulp.src('src/**/*.jade')
		.pipe(changed('app', {hasChanged: compareContents}))
		.pipe(jade())
		.pipe(gulp.dest('app'))
);

You can also specify a custom comparator function, which will receive the following arguments:

  • sourceFile (Vinyl file object)
  • destinationPath (string) - The destination for sourceFile as an absolute path

The function is expected to return sourceFile | Promise<sourceFile> if it passes some comparison or undefined | Promise<undefined>. Examples.

transformPath

Type: Function

Function to transform the path to the destination file. Should return the absolute path to the (renamed) destination file.

Useful if you rename your file later on, like in the below example:

export const marked = () => (
	gulp.src('src/content/about.md')
		.pipe(changed('dist', {
			transformPath: newPath => path.join(path.dirname(newPath), path.basename(newPath, '.md'), 'index.html')
		}))
		.pipe(marked())
		.pipe(rename(newPath => path.join(path.dirname(newPath), path.basename(newPath, '.md'), 'index.html')))
		.pipe(gulp.dest('dist'))
);

In-place change monitoring

If you're looking to process source files in-place without any build output (formatting, linting, etc), have a look at gulp-changed-in-place.

gulp-changed's People

Contributors

adamkiss avatar agarzola avatar ai avatar alexgorbatchev avatar alkorlos avatar amio avatar appleboy avatar arthurvr avatar daviskoh avatar escorponox avatar gavinaiken avatar generalov avatar grig0ry avatar kevva avatar mikaelbr avatar milang avatar mudcube avatar omgimalexis avatar petergoes avatar platy11 avatar richienb avatar sindresorhus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gulp-changed's Issues

Run tests on newer node versions

At the moment the .travis.yml file looks like this:

sudo: false
language: node_js
node_js:
  - 'iojs'
  - '0.12'
  - '0.10'

We are only testing against older versions of node - iojs, 0.12, 0.10. I think it would be helpful to test on newer node versions, as many people do not use these older versions anymore.

@sindresorhus If you are happy to add more versions, I would be happy to start a PR.

Unsure about this plugin

I don't know where else to post this. Gulp-changed doesn't work as expected. I have a source directory and a destination directory. I run a task that compiles typescript, using the source dir as the gulp.src. It's being triggered by a watch task that watches the same source dir. My issue is that every time the task runs it executes on ALL the files, not just the changed files. I'm looking at the docs, and there's something that doesn't make sense to me. Why does the changed() function need the DEST dir as a parameter. Why would gulp-changed care at all about the DEST? It should be only looking at the source file, and pass through files that have changed since last run. Why would it watch the DEST dir? Maybe this plugin does something totally different than what I'm getting from the description. I would assume it would just keep an eye on your input files, and filter out non-changed ones every time it runs. In that case, it would never need to watch or look at the destination files. Please someone enlighten me, super confused.

EDIT: The docs say:

changed(destination, [options])

destination

Type: string Function

Destination directory. Same as you put into gulp.dest().

This is needed to be able to compare the current files with the destination files.

Can also be a function returning a destination directory path.

"Destination directory. This is needed to be able to compare the current files with the destination files." <- that makes no sense. The DEST files will ALWAYS be different than the SOURCE files if you're processing them in any way, which would always result in ALL files being passed. What am I missing here, this really seems totally wrong to me.

Extension mapping

so I fix gulp-changed/index.js from line 74

if (opts.extension) {                                                                                                                                                                                                             
    if(typeof opts.extension === "string"){ //replace all
        newPath = gutil.replaceExtension(newPath, opts.extension);
    }else{
        for (var key in opts.extension){
            if(path.extname(newPath) === key){
                newPath = gutil.replaceExtension(newPath, opts.extension[key]);
            }
        }
    }
}

and use like this:

.pipe(GulpChanged(distPath, {extension: {'.handlebars': '.handlebars.js'}}))

is that ok ?

All files are compiled on any change

I am using version .2

Whenever I change any less file all files are recompiled and then reloaded.
I cant figure why

var gulp = require('gulp');  
var less = require('gulp-less');  
var refresh = require('gulp-livereload');  
var changed = require('gulp-changed');
var lr = require('tiny-lr');  
var server = lr();

gulp.task('styles', function() {  
    gulp.src(['./core/theme/**/*.less'])
        .pipe(changed('./core/theme/**/*.less',{extname:'css'}))
        .pipe(less())
        .pipe(gulp.dest('./core/theme/'))
        .pipe(refresh(server))
})

gulp.task('lr-server', function() {  
    server.listen(35729, function(err) {
        if(err) return console.log(err);
    });
})

gulp.task('default', function() {  
    gulp.run('lr-server', 'styles');

    gulp.watch('core/theme/**/*.less', function(event) {
        gulp.run('styles');
    })
})

Compare against concatenated file?

Is there a way to compare the file against a file of a different name?

For instance if the file has no destination because it is being concatenated with a number of other files. It would be nice to be able compare the file against the file that is the result of the concatenation.

Maybe allow destination to be a directory or a file?

ex.
partial1.js and partial2.js are concatenated into main.js

__ assets
  |__ partials
  |  |__ partial1.js
  |  |__ partial2.js
  |__ main.js

Not works if source and destination files is same

I think it would be useful for code formatting on the fly with fixmjs or esformatter.

Example:

var gulp = require('gulp');
var changed = require('gulp-changed');
var fixmyjs = require('gulp-fixmyjs');

gulp.task('fixmyjs', function () {
  gulp.src('*.js', {base: '.'})
    .pipe(changed('.'))
    .pipe(fixmyjs())
    .pipe(gulp.dest('.'));
});

gulp.task('watch', function () {
  gulp.watch('*.js', ['fixmyjs']);
});

gulp.task('default', ['fixmyjs', 'watch']);

If one of the files changed, triggered once, but nothing happen.
With different base and dest works perfectly.

Tested on Ubuntu 14.10 and Windows 8. Nodejs 0.12.0

extension option

Hi,

I just test your gulp plugin. Looks promising.
But the plugin cannot currently check generated file like jade or stylus.

Because the file.relative is changed in this case (index.jade and main.styl becomes index.html and main.css)
https://github.com/sindresorhus/gulp-changed/blob/master/index.js#L25

A nice addition could swap the file.relative extension in some case. Pehaps something like that:

gulp.task('jade', function() {
  gulp.src('./src/**/*.jade')
    .pipe(changed('./app/', {
        extension:[{jade:'html'}]
      ))
    .pipe(jade())
    .pipe(gulp.dest('./app/'))
});

gulp.task('default', function() {
  gulp.watch(["./src/**/*.jade"], function() {
    gulp.run('jade')
  });
});

What do you think?

hasChanged function using Git log

I guess this is a feature request but I'll try and implement myself. Want to document use case and my progress, see if anyone else has ideas, suggestions or is interested.

If I store binary files, such as images in Git LFS. When I checkout the files they all get a modified/created date of the time the files are checked out.

Two solutions:

  1. Update the timestamp.
git ls-tree -r --name-only HEAD | while read filename; do 
  unixtime=$(git log -1 --format="%at" -- "${filename}")
  touchtime=$(date -d @$unixtime +'%Y%m%d%H%M.%S')
  touch -t ${touchtime} "${filename}"
done
  1. Use gulp-git in git-changed.

I think the second option might be worth perusing and profiling for relative performance? There is potential for half the read I/O none of the write I/O.

gulp-changed does not overwrite files with different content

If I make two files in two sibling directories with different content:

nvioli$ echo "a" > test1/file.txt
nvioli$ echo "b" > test2/file.txt

then output the first one to a destination folder, and try to overwrite it with the second one, filtering with gulp-changed using the Sha1Digest comparator:

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

gulp.task('test1', function(){
        return gulp.src("test1/file.txt")
            .pipe(gulp.dest("dst"))
    });

gulp.task('test2', function(){
        return gulp.src("test2/file.txt")
            .pipe(changed("dst"), {hasChanged: changed.compareSha1Digest})
            .pipe(gulp.dest("dst"))
    });

nvioli$ gulp test1
[16:18:01] Using gulpfile ~/git/node/gulpfile.js
[16:18:01] Starting 'test1'...
[16:18:01] Finished 'test1' after 12 ms
nvioli$ gulp test2
[16:18:16] Using gulpfile ~/git/node/gulpfile.js
[16:18:16] Starting 'test2'...
[16:18:16] Finished 'test2' after 22 ms

I would expect the file to be overwritten since the source file in test2 differs in content from the existing one in the dst folder, but this is not the case:

nvioli$ cat dst/file.txt
a

Can someone please clear up my misunderstanding?

compareLastModifiedTime does not work

compareLastModifiedTime does not work properly in gulp4 environment.

This is a display of the comparison content.

process.stdout.write(sourceFile.stat.mtimeMs + ' > ' + targetStat.mtimeMs + "\n");

if (sourceFile.stat && sourceFile.stat.mtimeMs > targetStat.mtimeMs) {
 ...
1560691395680.4546 > 1560691395680

The original file mtimeMs has decimal places, so the file will be copied no matter how many times it is executed.

It worked fine by adding Math.floor ().

if (sourceFile.stat && Math.floor(sourceFile.stat.mtimeMs) > Math.floor(targetStat.mtimeMs)) {
  • macOS 10.14.5
  • Node 10.15.3
  • gulp 4.0.2
  • gulp-changed 4.0.0

Does gulp-changed work with jade features?

Hey.

I tried gulp-changed but with not too much luck I'm afraid.

I output jade compilation to an out directory.

Let's say for example I have a watch task watching for changes in all jade files and then only compiling document files with the following

gulp.task('jade:compile', function(event) {
  return gulp.src(sources.jadeCompile, {base: "src/jade/"})
    .pipe(plumber())
    // THIS IS NOT WORKING
    // .pipe(changed(destinations.docs, {
    //   extension: '.html'
    // }))
    .pipe(jade({
      pretty: true
    }))
    .pipe(gulp.dest(destinations.docs));
});

Say my index.jade file includes header.jade. If I make a change to header.jade the compilation task is fired but gulp-changed will decide that the files haven't changed so there is no need for them to be compiled. Therefore, making changes to my layout block files means that my documents won't actually be recompiled even though the content has changed.

@jh3y

compareLastModifiedTime with replaced files

Hi,

if I replace 1 file with another file than the compareLastModifiedTime method won't work if the new file was modified earlier. I think this method should also check the birthtime from the stats

My suggestion is to replace this:
Math.floor(sourceFile.stat.mtimeMs) > Math.floor(targetStat.mtimeMs)

With something like this:

Math.max(
				Math.floor(sourceFile.stat.mtimeMs),
				Math.floor(sourceFile.stat.birthtimeMs),
			) > Math.floor(targetStat.mtimeMs)

Confused about when to use compareContents

Regarding the built-in compareContents comparator, won't comparing source content to target content pass every file through? Assuming that the gulp task performs some kind of transformation on the source content. E.g. a source .njk file will never be the same as the compiled .html file. How is this comparator intended to be used?

SRC Variable - Array Capabilities

Hey it would be wonderful if the SRC variable could accept an array of strings that then could be compared in the destination.

Example

'use strict';

const changed = require('gulp-changed');
const eslint = require('gulp-eslint');
const gulp = require('gulp');
const path = require('path');
const rootDir = path.join(__dirname, '..');

const changedOptions = {
  cwd: rootDir
};

gulp.task('lint:js', () => {
  const files = [
    'src/resources/base/**/*.js',
    'src/resources/components/**/*.js',
    'src/resources/data/**/*.js',
    'src/resources/layouts/**/*.js',
    'src/resources/pages/**/*.js',
    'src/resources/patterns/**/*.js',
    'src/resources/xml/**/*.js',
    'gulp-tasks/**/*.js'
  ];
  return gulp.src(files)
    .pipe(changed('build/resources/', changedOptions))
    .pipe(eslint())
    .pipe(eslint.format());
});

when new files, it should be runing twice?

When I first run the gulp-changed in my project or I add new files in my project, the new files wouldn't pass though gulp-changed, beause

fs.stat(targetPath, function (err, targetStat) {  // targetPath isn't exist

This problem can be fixed, or I have to require other plugin?

thx

I am doing something wrong..

gulp.task('copy');

gulp.task('copy', function () {
return gulp.src(SRC)
.pipe(changed(DEST))
.pipe(gulp.dest(DEST));
});

Is it simply not possible to use like this ? I am used to GRUNT so not really got the hang of the pipe way forgive me for adding this as an issue - here is prolly usr error

doesn't work for me

Hello, I have a piece of code like this, and adding 'gulp-changed' changed nothing; all the files are processed, еvery time. I wonder why.

var gulp        = require('gulp');
var changed     = require('gulp-changed');
var imagemin    = require('gulp-imagemin');
var pngquant    = require('imagemin-pngquant');
var imageResize = require('gulp-image-resize');
var rename      = require('gulp-rename');

var img_src = ['_img/**/*.jpg', '_img/**/*.png'];
var img_dest = '_site/img';

gulp.task('resize-xl', function () {
    return gulp.src(img_src)
    .pipe(changed(img_dest))
    .pipe(imageResize({
      width : 2048,
      crop : false,
      upscale : true,
      sharpen: false,
      quality: 1
    }))
    .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
        .pipe(rename(function (path) {
          path.basename += "-2048";
        }))
        .pipe(gulp.dest(img_dest));
});

Error with gulp-ruby-sass 1.0

  return $.rubySass('app')
    .on('error', $.util.log)
    .on('error', $.util.beep)
    .pipe($.changed('.tmp'))
    .pipe(gulp.dest('.tmp'))

app/node_modules/gulp-changed/index.js:31
            if (sourceFile.stat.mtime > targetStat.mtime) {
                               ^
TypeError: Cannot read property 'mtime' of null
  at app/node_modules/gulp-changed/index.js:31:23
  at Object.oncomplete (fs.js:108:15)

Should gulp-changed work with gulp-ruby-sass 1.0?

Still compiling everything

Hi @sindresorhus

Im trying to use your plugin for compiling Coffeescript

Im passing the coffee_source to the changed plugin since the idea is to only process changed .coffee files.

Heres my config:

gulp.task('script', function () {
  gulp.src([ options.COFFEE_SOURCE ])
    .pipe(changed( options.COFFEE_SOURCE ))
    .pipe(coffee({
        //bare: true,
        sourceMap: true
    })
    .on('error', gutil.log))
    .pipe(gulp.dest( options.COFFEE_DEST ))
    .pipe(livereload(server));
});

Still everything gets compiled every time:

[gulp] Running 'script'...
[gulp] Finished 'script' in 7.77 ms
[gulp] chapter2.js.map was reloaded.
[gulp] chapter2.js was reloaded.
[gulp] chapter3.js.map was reloaded.
[gulp] chapter3.js was reloaded.
[gulp] chapter4.js.map was reloaded.
[gulp] chapter4.js was reloaded.
[gulp] chapter5.js.map was reloaded.
[gulp] chapter5.js was reloaded.
[gulp] main.js.map was reloaded.
[gulp] main.js was reloaded.

Am I missing something?

cwd option

you should probably take the same args as .dest, cwd.

Question: Paths

What is considered as a destination?
Do for example both cases work:

  1. All files no matter where the come from go into one directory:
    e.g.
 var dest1 = paths.tmp + '/serve/assets/json/'
  gulp.src(paths.src + '/frontend/**/*.json')
    .pipe($.changed(dest1))
    .pipe($.rename({dirname: ''}))
    .pipe(gulp.dest(dest1));
  1. All files go into their relative directories
    e.g.
 var dest1 = paths.tmp + '/serve/'
  gulp.src(paths.src + '/frontend/**/*.json')
    .pipe($.changed(dest1))
    .pipe(gulp.dest(dest1));

I just found this on renaming the file itself:
#56

Allow to read files after mtime check

Thanks for awesome plugin. But I want to make it even faster. Right now we need to read all files in fulp-src and only then we will remove unchanged.

But we can read only changed files:

return gulp.src('src/*.js', { read: false })
  .pipe( changed('dest/') )
  .pipe( readFile )

Unfortunately, file.isNull() check in yor plugin broke my perfomance utopia :(.

Maybe we can move it to compareSha1Digest? Because compareLastModifiedTime doesn’t need file content.

@sindresorhus

Errors when files are deleted

Ex. after deleting a file being watched:

/Users/ccheever/exponent-server/node_modules/gulp-changed/index.js:31
            if (sourceFile.stat.mtime > targetStat.mtime) {
                               ^
TypeError: Cannot read property 'mtime' of null
    at /Users/ccheever/exponent-server/node_modules/gulp-changed/index.js:31:23
    at FSReqWrap.oncomplete (fs.js:78:15)

I think the correct behavior is that the file should be reported as changed.

could I get the unchanged part?

Id like to remove all the unchanged files(by using gulp-clean) only. now Ive successfully got the changed part by gulp-changed, but is here any method to get the opposed part(unchanged files)?

Custom comparator

Hi,
I'm having problems with writing a custom comparator and I can't find any example of it for Scss to get started. I have a main.scss file and bootstrap.scss and both have imports/partials. I'd like gulp-changed to detect a change in any import. Could you please help me with the code or linking an example? Thanks.
Here is my current gulp task:

gulp.task('sass', function() {
    gulp.src('./app/scss/**/*.scss')
        .pipe(changed('./app/styles', {
          extension: '.css'
        }))
        .pipe(sourcemaps.init())
        .pipe(sass().on('error', sass.logError))
        .pipe(autoprefixer())
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest('./app/styles'))
        .pipe(browserSync.stream({match: '**/*.css'}));
});

compareLastModifiedTime does not work in Windows

The built in compareLastModifiedTime didn't work for me. On Windows the mtime of a file is rounded to seconds. Images created by people on a Mac, on the project I'm working on, have mliliseconds. When my task runs its creates the target file, and rounds milliseconds off. Subsequent runs it doesn't realize the source hasn't changed.

For example here is the source and target mtimes it was seeing.
1446818873134 > 1446818873000

Below is the method I used:

var compareLastModifiedTime = function(stream, cb, sourceFile, targetPath) {
    fs.stat(targetPath, function (err, targetStat) {
        if (targetStat === undefined) {
            stream.push(sourceFile);
        } else {
            var sourceMTime = sourceFile.stat.mtime / 1000 >> 0;
            var targetMTime = targetStat.mtime / 1000 >> 0;

            if (sourceMTime > targetMTime) {
                stream.push(sourceFile);
            }
        }
        cb();
    });
};

(NOTE: The bitwise math below is to round the float to an int. It's the quickest way according to: http://jsperf.com/math-floor-vs-math-round-vs-parseint/2)

Thanks,
David

changed.compareContents fails when directories are included

So when I run gulp-changed on a set of files and directories, it will fail with this error:

return gulp.src('./dist/**/*')
    .pipe(plugins.changed('distStaging', { hasChanged: plugins.changed.compareContents }))
    .pipe(gulp.dest('upload'))
;
(node:45206) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error in plugin 'gulp-changed'
Message:
    EISDIR: illegal operation on a directory, read
Details:
    errno: -21
    code: EISDIR
    syscall: read
    fileName: /Users/thomaskekeisen/Projects/thomaskekeisen-de/dist/de
(node:45206) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

A fix is to "skip" the directories:

// Only push through files with different contents than the destination files
function compareContents(stream, sourceFile, targetPath) {
	if (sourceFile.stat.isDirectory()) {
		return new Promise(function (fulfill, reject) {
			fulfill();
		});
	}

	return readFile(targetPath)
		.then(targetData => {
			if (sourceFile.isNull() || !sourceFile.contents.equals(targetData)) {
				stream.push(sourceFile);
			}
		});
}

1.2.0 - file is not defined

Using gulp-changed 1.1.1 I have no issues. Upgrading to 1.2.0 I end up with the following error:

c:\Users\cheath\Documents\dashboard\node_modules\gulp-changed\index.js:44
        cb(null, file);
                 ^
ReferenceError: file is not defined
    at c:\Users\cheath\Documents\dashboard\node_modules\gulp-changed\index.js:44:13
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:367:12)

The gulp task that causes this error:

var changed = require("gulp-changed");

    return gulp.src("webfonts/**/*")
    .pipe(changed(devFolder + "/webfonts", {hasChanged: changed.compareSha1Digest}))
    .pipe(gulp.dest(devFolder + "/webfonts"))
    .pipe(gulp.dest(prodFolder + "/webfonts"));

Many of my other tasks cause the same error. This was just the simplest case that caused the error.

I should note that some of my tasks do succeed with the same basic invocation of changed.

Question on use case scenario

So I took a quick look into the code and seems like it's a simple file path comparison between SRC and DEST.

What if I'm revving my file names between SRC and DEST, or compressing multiple files from SRC into one in DEST? Is there any way to still taking advantage of this lib in those cases?

allow multiple dest function calls

When setting dest as a function, I may want to generate dest dynamically:

// due to complicated or bad structure
function(file){
  return newPath( file )
}

Currently if dest is passed as a function, it is called only once, and that call's result is used ever since. Maybe we should allow multiple call to dest function. (it is the same behavior as gulp.dest)

For now I'm using a local variable copy of dest to do this. Link.

Anyway to use Sass partials?

I got the plugin to work great with files named the same as their dist offspring, however, it ignores files like _footer.scss because a footer.css doesn't exist. It's included in main.css which technically doesn't change. Is there any way to make gulp-changed work with Sass partials?

Pass all files if one of them changed, otherwise end stream

I've been trying to improve my project towards incremental builds, and I'm stuck between gulp-changed and gulp-watch, with neither of them offering what I'm looking for. In the end, I think gulp-changed is the best place to put what I have in mind.

My scenario is as follow:

I process (lint/hint, uglify/csso/less/minify/imagemin, concat, rename, output to dist folder) my resources (js+css+html+img), and I've made it so I can run all 4 subtasks in parallel already. The thing is, if I .pipe(changed()) those processes, I'd be getting incomplete output after the minification process because only the files that were modified are passed down the pipe. gulp-watch fixed that with an option to emit all files, but I don't want a watch task.
What I'm trying to accomplish is:

gulp.src(['glob'])
  .pipe(changed())
  .pipe(allTheProcessingAndStuff())
  .pipe(concat())
  .pipe(gulp.dest());
  • Files changed since last run ? (n = number of modified files)
    • Yes (n > 1): pass all files in 'glob' down the pipe
    • No (n == 0): end the pipe (I'm guessing it's feasible using stream events)

The only thing I'm not sure that can be done is ending the pipe from withing a stream eater gracefully.

The discussion regarding the emit all feature on gulp-watch can be found on gulpjs/gulp#13 and gulpjs/gulp#84.

If you have any insights about how I can improve this process without having to use watch tasks, I'll be gratefull to know.

compareLastModifiedTime() - fs.stat ENOENT

Hi. I'm experiencing some unexpected behavior when files are being compared for changes, specifically in the use of fs.stat. My task watches for changes to a set of files and simply copies them to a destination when there's a change. Using gulp-changed, when a file within the stream changes all files are copied instead of only just the one that has changed.

gulp.task('cgi', ['clean cgi'], function() {
    gulp.src(pkg.paths.src + pkg.paths.cgi + '**/*')
        .pipe($.changed(output + pkg.paths.cgi))
        .pipe(gulp.dest(output + pkg.paths.cgi))
});

gulp.task('watch', function() {
    gulp.watch(pkg.paths.src + pkg.paths.cgi + '**/*', ['cgi']);
});

Investigating further I found that when compareLastModifiedTime performs fs.stat, it fails thus bypassing the !fsOperationFailed block. I've verified the paths given to fs.stat are their absolute paths. Here is the error given when gulp-changed performs fs.stat in compareLastModifiedTime.

{ [Error: ENOENT, stat '/Users/christopher/PQ/pq-git/build/development/cgi/cgi-bin/api.php']
  errno: -2,
  code: 'ENOENT',
  path: '/Users/christopher/PQ/pq-git/build/development/cgi/cgi-bin/api.php' }

In my Gulpfile.js I created a simple task to fs.stat the exact path (copied from the error in console). Here fs.stat successfully identified the file.

gulp.task('stat', function() {
    fs.stat('/Users/christopher/PQ/pq-git/build/development/cgi/cgi-bin/api.php', function (err, targetStat) {
        console.log('err', err);
        console.log('targetStat', targetStat);
    });
});

// console.log output
err null
targetStat { dev: 16777220,
  mode: 16877,
  nlink: 8,
  uid: 501,
  gid: 20,
  rdev: 0,
  blksize: 4096,
  ino: 6525662,
  size: 272,
  blocks: 0,
  atime: Thu Apr 09 2015 09:31:50 GMT-0400 (EDT),
  mtime: Thu Apr 09 2015 09:31:48 GMT-0400 (EDT),
  ctime: Thu Apr 09 2015 09:31:48 GMT-0400 (EDT),
  birthtime: Thu Apr 09 2015 09:31:48 GMT-0400 (EDT) }

I switched the comparator to use changed.compareSha1Digest and it fails as well. I'm using node v0.12.2 (Mac OS 10.9.5) and the current version of gulp-changed. Please let me know what further information I can provide.

All files are passed through all the time.

I'm certain I'm doing something really obvious here, but for the life of me I can't resolve this.

var gulp = require("gulp");
var changed = require("gulp-changed");

var HTML_GLOB = "src/*.html";

gulp.task("watch", function() {
    gulp.watch(HTML_GLOB, ["copyHTML"]);
});

gulp.task("copyHTML", function() {
    return gulp.src(HTML_GLOB)
        .pipe(changed("out"))
        .pipe(gulp.dest("out"));
});

All HTML files are copied every time one changes. I've verified that the modified dates on the other HTML files have not changed.

it doesn't work with gulp-webpack。

my gulp task config is:

gulp.task('build:js', () => {
  return gulp.src(cfg.path.js)
    .pipe(changed(cfg.path.jsdest))
    .pipe(named())
    .pipe(webpack({
      devtool:'source-map',
      output:{
        filename:'[name].js',
      },
      module: {
        loaders: [
          {
            test: /\.js?$/,
            loader: 'babel-loader',         
            exclude: /node_modules/, 
            query: {
              presets: ['es2015'] 
            }
          },
        ]
      }
    }, null, function (err, stats) {
      /* Use stats to do more things if needed */
      if (err) throw new gutil.PluginError("webpack:build-js", err);
      gutil.log("[webpack:build-js]", stats.toString({
        colors: true
      }));
    }))
    .pipe(gulp.dest(cfg.path.jsdest));
})

but when I change js,all the js files will compile,can you tell me who to deal this problem?

Replace deprecated dependency gulp-util

gulp-util has been recently deprecated. Continuing to use this dependency may prevent the use of your library with the latest release of Gulp 4 so it is important to replace gulp-util.

The README.md lists alternatives for all the components so a simple replacement should be enough.

Your package is one of the most popular packages still relying on gulp-util, it would be good to publish a fixed version to npm as soon as possible.

See:

not working with gulp-rename?

If some can confirm this I'll be grateful. I have a simple task as test, tried with other plugins but it seems to happen only with gulp-rename. When combined with gulp-rename all files pass.

gulp.task('minifyJs', function () {
    return gulp.src('html/assets/js/*.js')
    .pipe(changed('deploy/assets/js'))
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('deploy/assets/js'))
  });

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.

  • 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.

  • 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.

  • D3 photo D3

    Data-Driven Documents codes.