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