-
Notifications
You must be signed in to change notification settings - Fork 42
/
buildProduction
executable file
·245 lines (236 loc) · 11.3 KB
/
buildProduction
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#!/usr/bin/env node
var optimist = require('optimist'),
commandLineOptions = optimist
.usage('$0 --root <inputRootDirectory> --outroot <dir> [options] <htmlFile(s)>')
.options('h', {
alias: 'help',
describe: 'Show this help',
type: 'boolean',
default: false
})
.options('root', {
describe: 'Path to your web root',
type: 'string',
demand: true
})
.options('outroot', {
describe: 'Path to the output folder. Will be generated if non-existing',
type: 'string',
demand: true
})
.options('cdnroot', {
describe: 'URI root where the static assets will be deployed. Must be either an absolute or a protocol-relative url.',
type: 'string',
demand: false
})
.options('cdnoutroot', {
describe: 'Path to the CDN output folder. Will be generated if non-existing',
type: 'string',
demand: false
})
.options('exclude', {
describe: 'Url pattern to exclude from the build. Supports * wildcards. You can create multiple of these: --exclude *.php --exclude http://example.com/*.gif',
type: 'string',
demand: false
})
.options('label', {
describe: 'Registers labels as custom protocols for path resolving. You can create multiple of these: --label <labelName>=<dir> --label <otherLabelName>=<otherDir>',
type: 'string',
demand: false
})
.options('parentdir', {
describe: 'If an unknown label (scheme) is found, look for at parent dir of that name before failing (breaks custom protocols)',
type: 'boolean',
demand: false
})
.options('locale', {
describe: 'Comma-separated list of locales to build seperate versions for',
type: 'string',
demand: false
})
.options('striponebootstrapper', {
describe: 'Removes the production part of the oneBootstrapper script that buildDevelopment injects to support localization (defaults to true if --locale is specified, false otherwise)',
type: 'boolean'
})
.options('defaultlocale', {
describe: 'The locale of the default value in one.tr statements and tags with a data-i18n attribute',
type: 'string',
default: 'en'
})
.options('optimizepngs', {
describe: 'Tries optimal palette reduction, removes ancillary chunks and tries for better compression',
type: 'boolean',
default: false
})
.options('inlinesize', {
describe: 'Inline CSS backgrounds below this threshold as data-uris',
default: 8192
})
.options('deferscripts', {
describe: 'Sets the "defer" attribute on all script tags',
type: 'boolean',
default: false
})
.options('asyncscripts', {
describe: 'Sets the "async" attribute on all script tags',
type: 'boolean',
default: false
})
.options('nocompress', {
describe: 'Prettifies HTML, CSS and Javascript for easier debugging',
type: 'boolean',
default: false
})
.options('mangletoplevel', {
describe: 'Wraps your javascript code in a function literal that pulls global variables into local variables for better minification. WARNING: This may break your JS',
type: 'boolean',
default: false
})
.options('manifest', {
describe: 'Generates an appcache manifest file with all static assets included',
type: 'boolean',
default: false
})
.options('less', {
describe: 'Translates .less files to CSS',
type: 'boolean',
default: false
})
.options('version', {
describe: 'Adds or updates <meta http-equiv="Content-Version" content="..."> to the specified value. Use {0} to refer to the current value, eg. --version {0}/production or --version `git describe --long --tags --always --dirty 2>/dev/null || echo unknown`',
type: 'string'
})
.check(function (argv) {
return typeof argv.inlinesize === 'number';
})
.demand(1)
.wrap(72)
.argv;
if (commandLineOptions.h) {
optimist.showHelp();
process.exit(1);
}
var _ = require('underscore'),
AssetGraph = require('assetgraph'),
oneBootstrapper = require('../lib/util/oneBootstrapper'),
query = AssetGraph.query,
urlTools = require('assetgraph/lib/util/urlTools'),
outroot = urlTools.fsDirToFileUrl(commandLineOptions.outroot),
cdnroot = commandLineOptions.cdnroot && urlTools.ensureTrailingSlash(commandLineOptions.cdnroot),
cdnoutroot = commandLineOptions.cdnoutroot && urlTools.fsDirToFileUrl(commandLineOptions.cdnoutroot),
localeIds = commandLineOptions.locale && _.flatten(_.flatten([commandLineOptions.locale]).map(function (localeId) {return localeId.split(",");})),
stripOneBootstrapper = commandLineOptions.striponebootstrapper || !commandLineOptions.locale,
blacklistUrlRegExp = /^$/,
cdnrootIsProtocolRelative = false;
if (/^\/\//.test(cdnroot)) {
cdnrootIsProtocolRelative = true;
cdnroot = 'http:' + cdnroot;
}
if (commandLineOptions.exclude) {
blacklistUrlRegExp = new RegExp('(?:' +
_.flatten(_.flatten([commandLineOptions.exclude])).map(function (wildcard) {
return wildcard.replace(/[\.\+\{\}\[\]\(\)\?\^\$]/g, '\\$&').replace(/\*/g, '.*?');
}).join('|') +
')');
}
require('../lib/registerTransforms');
new AssetGraph({root: commandLineOptions.root})
.on('afterTransform', function (transform, elapsedTime) {
console.log((elapsedTime / 1000).toFixed(3) + " secs: " + transform.name);
})
.on('error', function (err) {
console.error(err.stack);
process.exit(1);
})
.registerRequireJsConfig()
.registerLabelsAsCustomProtocols(commandLineOptions.label, {installFindParentDirectoryAsDefault: commandLineOptions.parentdir})
.loadAssets(commandLineOptions._.map(urlTools.fsFilePathToFileUrl))
.populate({
followRelations: query.or({to: {type: 'I18n'}},
{type: query.not(['JavaScriptOneInclude', 'JavaScriptExtJsRequire', 'JavaScriptCommonJsRequire', 'HtmlAnchor']), to: query.and({url: query.not(/^https?:/)}, {url: query.not(blacklistUrlRegExp)})})
})
.if(stripOneBootstrapper)
.stripOneBootstrapper()
.else()
.stripDevelopmentModeFromOneBootstrapper({type: 'Html', isInitial: true})
.if(cdnroot)
.queue(function addCdnRootToOneBootstrapper(assetGraph) {
oneBootstrapper.findOneBootstrappersInGraph(assetGraph).forEach(function (javaScript) {
javaScript.parseTree[1].splice(1, 0, ['stat', ['assign', true, ['dot', ['name', 'one'], 'cdnRoot'], ['string', cdnroot]]]);
});
})
.endif()
.endif()
.if(commandLineOptions.version)
.addContentVersionMetaElement({type: 'Html'}, commandLineOptions.version, true)
.endif()
.if(commandLineOptions.less)
// Replace Less assets with their Css counterparts:
.compileLessToCss({type: 'Less'})
// Kill in-browser less compiler and remove its incoming relations:
.removeAssets({url: /\/less(?:-\d+\.\d+\.\d+)?(?:\.min)?\.js$/}, true)
// Find and populate CssImage relations from the compiled Less assets:
.populate({from: {type: 'Css'}})
.endif()
.removeRelations({type: 'JavaScriptOneInclude', to: {type: ['Css', 'JavaScript']}}, {detach: true, unresolved: true})
.convertCssImportsToHtmlStyles()
.removeAssets({isEmpty: true, type: ['Css', 'JavaScript']}, true)
.externalizeRelations({from: {type: query.not('Htc')}, type: ['HtmlStyle', 'HtmlScript'], node: function (node) {return !node.hasAttribute('nobundle');}})
.mergeIdenticalAssets(query.or({isImage: true}, {type: ['JavaScript', 'Css']}))
.spriteBackgroundImages()
.postProcessCssImages()
.if(commandLineOptions.optimizepngs)
.optimizePngs()
.endif()
.bundleRequireJs({type: 'Html'})
.bundleRelations({type: 'HtmlStyle', to: {type: 'Css'}, node: function (node) {return !node.hasAttribute('nobundle') && !node.hasAttribute('localize');}})
.bundleRelations({type: 'HtmlScript', to: {type: 'JavaScript'}, node: function (node) {return !node.hasAttribute('nobundle') && !node.hasAttribute('localize');}})
.inlineCssImagesWithLegacyFallback({type: 'Html', isInline: false}, commandLineOptions.inlinesize)
.if(commandLineOptions.mangletoplevel)
.pullGlobalsIntoVariables({type: 'JavaScript'})
.endif()
.if(!commandLineOptions.nocompress)
.compressJavaScript({type: 'JavaScript'}, 'uglifyJs', {toplevel: commandLineOptions.mangletoplevel})
.endif()
.if(localeIds)
.cloneForEachLocale({type: 'Html', isInitial: true}, {localeIds: localeIds, defaultLocaleId: commandLineOptions.defaultlocale})
.runJavaScriptConditionalBlocks({isInitial: true}, 'localize', true)
.bundleRelations({type: 'HtmlScript', to: {type: 'JavaScript'}, node: function (node) {return !node.hasAttribute('nobundle');}})
.endif()
.removeNobundleAttribute({type: ['HtmlScript', 'HtmlStyle']})
.removeAssets({type: 'I18n'}, true)
.minifyAssets()
.inlineRelations({
type: ['HtmlStyle', 'HtmlScript'],
from: {isInline: false}, // Excludes relations occurring in conditional comments
to: function (asset) {return asset.isAsset && asset.rawSrc.length < 4096;}
})
.if(commandLineOptions.manifest)
.addCacheManifest({isInitial: true})
.endif()
.if(commandLineOptions.nocompress)
.prettyPrintAssets({type: ['Html', 'JavaScript', 'Css']})
.endif()
.setAsyncOrDeferOnHtmlScripts({to: {isInline: false, url: /^file:/}}, commandLineOptions.asyncscripts, commandLineOptions.deferscripts)
.omitGetStaticUrlFunctionCall()
.inlineRelations({type: 'JavaScriptOneGetText'})
.moveAssetsInOrder({isInitial: query.not(true), type: query.not('CacheManifest')}, function (asset, assetGraph) {
var targetUrl = "/static/";
// Conservatively assume that all one.getStaticUrl relations pointing at non-images are intended to be fetched via XHR
// and thus cannot be put on a CDN because of same origin restrictions:
if (cdnroot && (asset.isImage || assetGraph.findRelations({to: asset, type: 'StaticUrlMapEntry'}).length === 0)) {
targetUrl = cdnroot;
if (cdnrootIsProtocolRelative) {
assetGraph.findRelations({to: asset}).forEach(function (incomingRelation) {
incomingRelation.hrefType = 'protocolRelative';
});
}
}
return targetUrl + asset.md5Hex.substr(0, 10) + asset.extension + asset.url.replace(/^[^#\?]*(?:)/, ''); // Preserve query string and fragment identifier
})
.writeAssetsToDisc({url: /^file:/}, outroot)
.if(cdnroot)
.writeAssetsToDisc({url: query.createPrefixMatcher(cdnroot)}, cdnoutroot || outroot, cdnroot)
.endif()
.writeStatsToStderr()
.run();