UNPKG

2.78 kBJavaScriptView Raw
1/** Copyright (c) 2018 Uber Technologies, Inc.
2 *
3 * This source code is licensed under the MIT license found in the
4 * LICENSE file in the root directory of this source tree.
5 *
6 * @flow
7 */
8
9/* eslint-env node */
10
11const winston = require('winston');
12
13const {Compiler} = require('../build/compiler');
14const {DevelopmentRuntime} = require('../build/dev-runtime');
15const {TestAppRuntime} = require('../build/test-runtime');
16const {execSync: exec} = require('child_process');
17
18exports.run = async function(
19 {
20 dir = '.',
21 test,
22 debug,
23 forceLegacyBuild = false,
24 port,
25 hmr,
26 open,
27 logLevel,
28 exitOnError,
29 } /*: any */
30) {
31 const logger = winston.createLogger({
32 format: winston.format.combine(
33 winston.format.colorize(),
34 winston.format.simple()
35 ),
36 });
37 logger.add(new winston.transports.Console({level: logLevel}));
38
39 const compiler = new Compiler({
40 env: 'development',
41 dir,
42 hmr,
43 forceLegacyBuild,
44 watch: true,
45 logger,
46 });
47
48 const devRuntime = new DevelopmentRuntime(
49 // $FlowFixMe
50 Object.assign(
51 {
52 dir,
53 port,
54 debug,
55 noOpen: !open,
56 },
57 hmr ? {middleware: compiler.getMiddleware()} : {}
58 )
59 );
60
61 const testRuntime = test
62 ? new TestAppRuntime({dir, overrideNodeEnv: true})
63 : null;
64
65 // $FlowFixMe
66 await Promise.all([devRuntime.start(), compiler.clean(dir)]);
67
68 const runAll = async () => {
69 try {
70 await Promise.all([
71 devRuntime.run(),
72 // $FlowFixMe
73 testRuntime ? testRuntime.run() : Promise.resolve(),
74 ]);
75 if (!open) {
76 logger.info(`Application is running on http://localhost:${port}`);
77 }
78 } catch (e) {} // eslint-disable-line
79 };
80
81 const watcher = await new Promise((resolve, reject) => {
82 const watcher = compiler.start((err, stats) => {
83 if (err || stats.hasErrors()) {
84 if (exitOnError) {
85 return reject(
86 new Error('Compilation error exiting due to exitOnError parameter.')
87 );
88 } else {
89 return resolve(watcher);
90 }
91 }
92 return runAll().then(() => resolve(watcher));
93 });
94 });
95
96 // Rerun for each recompile
97 compiler.on('done', () => {
98 if (debug) {
99 // make the default node debug port available for attaching by killing the
100 // old attached process
101 try {
102 exec('kill -9 $(lsof -n -t -i:9229)');
103 } catch (e) {} // eslint-disable-line
104 }
105 runAll();
106 });
107 compiler.on('invalid', () => devRuntime.invalidate());
108
109 function stop() {
110 watcher.close();
111 devRuntime.stop();
112 // $FlowFixMe
113 if (testRuntime) testRuntime.stop();
114 }
115
116 process.on('SIGTERM', () => {
117 stop();
118 });
119
120 return {
121 compiler,
122 stop,
123 };
124};