Last active
December 1, 2016 10:15
-
-
Save yukpiz/67dc27debdc38bc155f6355ae0bff7c5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
var gulp = require("gulp"), | |
fs = require("fs"), | |
watch = require("gulp-watch"), | |
plugins = require("gulp-load-plugins")(), | |
babelify = require("babelify"), | |
browserify = require("browserify"), | |
watchify = require("watchify"), | |
source = require("vinyl-source-stream"), | |
buffer = require("vinyl-buffer"); | |
gulp.task("watchjs", () => { | |
watchReadDirectory(); | |
watch(["./*.js"], {events: ['add', 'unlink']}, (e, done) => { | |
var file = getFileName(e.path); | |
if (e.event == "add") { | |
plugins.util.log(` added ${file}`); | |
startWatchify(file); | |
} else if (e.event == "unlink") { | |
plugins.util.log(` removed ${file}`); | |
var outpath = "../../../public/js/" + file; | |
fs.unlink(outpath, (err) => { | |
if (err != null) { | |
plugins.util.log(err); | |
} | |
}); | |
} | |
}); | |
}); | |
var getFileName = (path) => { | |
var s = path.split("/"); | |
return s[s.length -1]; | |
}; | |
var watchReadDirectory = () => { | |
fs.readdir(".", (err, files) => { | |
files.filter((file) => { | |
return fs.statSync(file).isFile() && /.*\.js$/.test(file) && !/^gulpfile\.js$/.test(file) | |
}).forEach((file) => { | |
startWatchify(file); | |
}); | |
}); | |
}; | |
var startWatchify = (file) => { | |
const srcDir = "."; | |
const outDir = "../../../public/js"; | |
if (file == "gulpfile.js") { | |
return; | |
} | |
let browserifyOp = { | |
entries: [srcDir + "/" + file], | |
transform: babelify.configure({presets: ["react"]}), | |
debug: true, | |
cache: {}, | |
packageCache: {}, | |
}; | |
let watchifyStream = watchify(browserify(browserifyOp)); | |
let execBundle = () => { | |
plugins.util.log(` building ${file}...`); | |
return watchifyStream | |
.bundle() | |
.on("error", plugins.util.log.bind(plugins.util, "Browserify Error")) | |
.pipe(source(file)) | |
.pipe(buffer()) | |
.pipe(gulp.dest(outDir)); | |
}; | |
watchifyStream.on("update", execBundle); | |
watchifyStream.on("log", plugins.util.log); | |
return execBundle(); | |
}; | |
gulp.task("default", ["watchjs"]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment