UNPKG

2.17 kBJavaScriptView Raw
1var createBundleGraphStream = require("../graph/make_graph_with_bundles").createBundleGraphStream;
2var recycle = require("../graph/recycle");
3var multiBuild = require("../stream/build");
4var createConcatStream = require("../bundle/concat_stream");
5var createWriteStream = require("../bundle/write_bundles").createWriteStream;
6var stealWriteStream = require("../stream/steal");
7var watch = require("../stream/watch");
8var defaults = require("lodash").defaults;
9
10module.exports = function(config, options){
11 var moment = require("moment");
12
13 defaults(options, {
14 sourceMaps: true,
15 minify: false,
16 quiet: true
17 });
18
19 var moduleName;
20
21 // A function that is called whenever a module is found by the watch stream.
22 // Called with the name of the module and used to rebuild.
23 function rebuild(moduleNames){
24 moduleName = moduleNames[0] || "";
25 moduleNames.forEach(function(moduleName){
26 graphStream.write(moduleName);
27 });
28 }
29
30 function log(){
31 var rebuiltPart = moduleName ? moduleName : "";
32 var time = "[" + moment().format("LTS") + "]";
33 console.error(time.red + (moduleName ? ":" : ""), rebuiltPart.green);
34 }
35
36 // Create an initial dependency graph for this config.
37 var initialGraphStream = createBundleGraphStream(config, options);
38 // Create a stream that is used to regenerate a new graph on file changes.
39 var graphStream = recycle(config);
40
41 // Create a build stream that does everything; creates a graph, bundles,
42 // and writes the bundles to the filesystem.
43 var buildStream = initialGraphStream
44 .pipe(graphStream)
45 .pipe(multiBuild(config, options))
46 .pipe(createConcatStream())
47 .pipe(createWriteStream())
48 .pipe(stealWriteStream());
49
50 // Watch the build stream and call rebuild whenever it changes.
51 var watchStream = watch(graphStream);
52 watchStream.on("data", rebuild);
53
54 buildStream.on("data", log);
55 graphStream.on("error", function(error){
56 // If this is a missing file add it to our watch.
57 if(error.code === "ENOENT" && error.path) {
58 console.error("File not found:", error.path);
59 watchStream.write(error.path);
60 }
61 });
62 buildStream.once("data", function(){
63 console.error("Watch mode ready.");
64 });
65
66 return buildStream;
67};