UNPKG

2.59 kBJavaScriptView Raw
1var bundleFilename = require("./filename");
2var dirname = require("path").dirname;
3var addSourceMapUrl = require("../bundle/add_source_map_url");
4var through = require("through2");
5var winston = require("winston");
6var minifySource = require("./minify_source");
7
8var denodeify = require("pdenodeify");
9var writeFile = denodeify(require("fs").writeFile);
10var mkdirp = denodeify(require("fs-extra").mkdirp);
11
12/**
13 * Writes bundles out to the file system.
14 * @param {Array} bundles - The bundles to be written out
15 * @param {Object} configuration - The build configuration object
16 * @return {Promise.<bundle[]>} A promise that resolves when bundles finished writing
17 */
18var writeBundles = module.exports = function(bundles, configuration) {
19 // Create the bundle directory
20 var bundleDirDef = configuration.mkBundlesPathDir();
21
22 var processBundle = function(bundle) {
23 var bundlePath = bundle.bundlePath;
24
25 // If the bundle is explicity marked as clean, just resolve.
26 if (bundle.isDirty === false) {
27 return Promise.resolve(bundle);
28 }
29
30 var sourceCode;
31 var sourceMap;
32
33 // minify concatenated source
34 return minifySource(bundle, configuration.options)
35 .then(function(minified) {
36 bundle.source = minified;
37
38 sourceCode = bundle.source.code;
39 if (configuration.options.sourceMaps) {
40 addSourceMapUrl(bundle);
41 sourceCode = bundle.source.code;
42 sourceMap = bundle.source.map;
43 }
44
45 // Log the bundles
46 winston.info("BUNDLE: %s", bundleFilename(bundle));
47 winston.debug(Buffer.byteLength(sourceCode, "utf8") + " bytes");
48
49 bundle.nodes.forEach(function(node) {
50 winston.info("+ %s", node.load.name);
51 });
52
53 return bundleDirDef;
54 })
55 // Once a folder has been created, write out the bundle source
56 .then(function() {
57 return mkdirp(dirname(bundlePath));
58 })
59 .then(function() {
60 return writeFile(bundlePath, sourceCode);
61 })
62 .then(function() {
63 if (sourceMap) {
64 return writeFile(bundlePath+".map", sourceMap);
65 }
66 })
67 .then(function() {
68 return bundle;
69 });
70 };
71
72 return Promise.all(bundles.map(processBundle));
73};
74
75/**
76 * Transform stream that writes the bundles to the filesystem
77 * @param {Object} [options] - An object of options
78 * @return {stream.Transform}
79 */
80writeBundles.createWriteStream = function() {
81 function write(buildResult, enc, done) {
82 var configuration = buildResult.configuration;
83 var bundles = buildResult.bundles;
84
85 writeBundles(bundles, configuration)
86 .then(function() {
87 done(null, buildResult);
88 })
89 .catch(done);
90 }
91
92 return through.obj(write);
93};