1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 | 'use strict';
|
20 |
|
21 | var exec = require('child_process').exec;
|
22 | var path = require('path');
|
23 | var fs = require('fs');
|
24 | var Util = require('./utils');
|
25 | var UglifyJS = require('uglify-js');
|
26 |
|
27 | var DEV_REGEX = /global\.__DEV__\s?=\s?true/;
|
28 | var DEV_FALSE = 'global.__DEV__ = false';
|
29 |
|
30 | function injectCodesToBase(config) {
|
31 | var entryInject = '\n\nrequire(\'AppRegistry\')\n';
|
32 | config.customEntries.forEach(function (entry) {
|
33 | if (entry.inject === false) {
|
34 | return;
|
35 | }
|
36 | var indexModule = path.resolve(config.root, entry.index);
|
37 | entryInject += 'require(\'' + indexModule + '\');\n';
|
38 | });
|
39 | var tmpEntry = path.resolve(config.root, config.baseEntry.index + '.tmp');
|
40 | if (fs.existsSync(tmpEntry)) {
|
41 | fs.unlinkSync(tmpEntry);
|
42 | }
|
43 | var originData = fs.readFileSync(config.baseEntry.index, 'utf-8');
|
44 | originData += entryInject;
|
45 | fs.writeFileSync(tmpEntry, originData);
|
46 | return tmpEntry;
|
47 | }
|
48 |
|
49 | function bundle(config, callback) {
|
50 | Util.ensureFolder(config.bundleDir);
|
51 |
|
52 | var tmpBase = injectCodesToBase(config);
|
53 | var bundlePath = path.resolve(config.bundleDir, 'index.bundle');
|
54 |
|
55 | var cmd = 'react-native bundle';
|
56 | cmd += ' --entry-file ' + tmpBase;
|
57 | cmd += ' --bundle-output ' + bundlePath;
|
58 | cmd += ' --assets-dest ' + config.bundleDir;
|
59 | cmd += ' --platform ' + config.platform;
|
60 |
|
61 | console.log('===[Bundle] Start!===');
|
62 | console.log(cmd);
|
63 | exec(cmd, function (error) {
|
64 | if (error) {
|
65 | callback(error);
|
66 | }
|
67 | var code = fs.readFileSync(bundlePath, 'utf-8');
|
68 | if (!config.dev) {
|
69 | var globalDev = DEV_REGEX.exec(code.substring(0, 5000));
|
70 | if (globalDev) {
|
71 | console.log('Replace ' + globalDev[0] + ' with ' + DEV_FALSE);
|
72 | code = code.replace(globalDev[0], DEV_FALSE);
|
73 | }
|
74 | fs.writeFileSync(bundlePath, code, 'utf-8');
|
75 | code = UglifyJS.minify(bundlePath, {
|
76 | compress: {
|
77 | sequences: false,
|
78 | global_defs: {
|
79 | __DEV__: false
|
80 | }
|
81 | },
|
82 | mangle: {
|
83 | except: ['__d', 'require', '__DEV__']
|
84 | }
|
85 | }).code;
|
86 | fs.writeFileSync(bundlePath + '.min', code, 'utf-8');
|
87 | }
|
88 | callback(error, code);
|
89 | fs.unlinkSync(tmpBase);
|
90 | }).stdout.pipe(process.stdout);
|
91 | }
|
92 |
|
93 | module.exports = bundle; |
\ | No newline at end of file |