UNPKG

2.85 kBJavaScriptView Raw
1/**
2 * Copyright 2015-present Desmond Yao
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * Created by desmond on 4/16/17.
17 *
18 */
19'use strict';
20
21var exec = require('child_process').exec;
22var path = require('path');
23var fs = require('fs');
24var Util = require('./utils');
25var UglifyJS = require('uglify-js');
26
27var DEV_REGEX = /global\.__DEV__\s?=\s?true/;
28var DEV_FALSE = 'global.__DEV__ = false';
29
30function 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
49function 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
93module.exports = bundle;
\No newline at end of file