forked from systemjs/plugin-css
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcss-builder.js
More file actions
83 lines (62 loc) · 2.6 KB
/
css-builder.js
File metadata and controls
83 lines (62 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
var CleanCSS = require('clean-css');
// it's bad to do this in general, as code is now heavily environment specific
var fs = System._nodeRequire('fs');
function escape(source) {
return source
.replace(/(["\\])/g, '\\$1')
.replace(/[\f]/g, "\\f")
.replace(/[\b]/g, "\\b")
.replace(/[\n]/g, "\\n")
.replace(/[\t]/g, "\\t")
.replace(/[\r]/g, "\\r")
.replace(/[\u2028]/g, "\\u2028")
.replace(/[\u2029]/g, "\\u2029");
}
var isWin = process.platform.match(/^win/);
function fromFileURL(address) {
address = address.replace(/^file:(\/+)?/i, '');
if (!isWin)
address = '/' + address;
else
address = address.replace(/\//g, '\\');
return address;
}
var cssInject = "(function(c){if (typeof document == 'undefined') return; var d=document,a='appendChild',i='styleSheet',s=d.createElement('style');s.type='text/css';d.getElementsByTagName('head')[0][a](s);s[i]?s[i].cssText=c:s[a](d.createTextNode(c));})";
module.exports = function bundle(loads, compileOpts, outputOpts) {
// SystemJS Builder 0.14 will write the stubs for use, we detect by the 3 argument over 2 argument bundle call
var writeStubs = typeof outputOpts == 'undefined';
outputOpts = outputOpts || compileOpts;
var loader = this;
var stubDefines = writeStubs ? loads.map(function(load) {
return (compileOpts.systemGlobal || 'System') + ".register('" + load.name + "', [], false, function() {});";
}).join('\n') : [];
var rootURL = loader.rootURL || fromFileURL(loader.baseURL);
var cssOptimize = outputOpts.minify && outputOpts.cssOptimize !== false;
var outFile = loader.separateCSS ? outputOpts.outFile.replace(/\.js$/, '.css') : rootURL;
var cleanCSS = new CleanCSS({
advanced: cssOptimize,
agressiveMerging: cssOptimize,
mediaMerging: cssOptimize,
restructuring: cssOptimize,
shorthandCompacting: cssOptimize,
target: outFile,
relativeTo: rootURL,
sourceMap: !!outputOpts.sourceMaps,
sourceMapInlineSources: outputOpts.sourceMapContents
}).minify(loads.map(function(load) {
return fromFileURL(load.address)
}));
if (cleanCSS.errors.length)
throw new Error('CSS Plugin:\n' + cleanCSS.errors.join('\n'));
var cssOutput = cleanCSS.styles;
// write a separate CSS file if necessary
if (loader.separateCSS) {
if (outputOpts.sourceMaps) {
fs.writeFileSync(outFile + '.map', cleanCSS.sourceMap.toString());
cssOutput += '/*# sourceMappingURL=' + outFile.split(/[\\/]/).pop() + '.map*/';
}
fs.writeFileSync(outFile, cssOutput);
return stubDefines;
}
return [stubDefines, cssInject, '("' + escape(cssOutput) + '");'].join('\n');
};