Refactors option forwarding from RN-cli to Metro

Reviewed By: jeanlauliac

Differential Revision: D6936821

fbshipit-source-id: aeaad43ca056cf0cb26255e426695f3bfb396368
This commit is contained in:
Maël Nison 2018-02-09 04:01:56 -08:00 committed by Facebook Github Bot
parent 07a79853ef
commit f12b07101e
1 changed files with 77 additions and 62 deletions

View File

@ -33,22 +33,27 @@ const {Terminal} = require('metro-core');
import type {ConfigT} from './Config'; import type {ConfigT} from './Config';
import type {GlobalTransformCache} from './lib/GlobalTransformCache'; import type {GlobalTransformCache} from './lib/GlobalTransformCache';
import type {Options as ServerOptions} from './shared/types.flow';
import type {Reporter} from './lib/reporting'; import type {Reporter} from './lib/reporting';
import type {RequestOptions, OutputOptions} from './shared/types.flow.js'; import type {RequestOptions, OutputOptions} from './shared/types.flow.js';
import type {Options as ServerOptions} from './shared/types.flow'; import type {TransformCache} from './lib/TransformCaching';
import type {Server as HttpServer} from 'http'; import type {Server as HttpServer} from 'http';
import type {Server as HttpsServer} from 'https'; import type {Server as HttpsServer} from 'https';
export type {ConfigT} from './Config'; export type {ConfigT} from './Config';
type DeprecatedMetroOptions = {|
resetCache?: boolean,
|};
type PublicMetroOptions = {| type PublicMetroOptions = {|
...DeprecatedMetroOptions,
config?: ConfigT, config?: ConfigT,
globalTransformCache?: ?GlobalTransformCache, globalTransformCache?: ?GlobalTransformCache,
maxWorkers?: number, maxWorkers?: number,
port?: ?number, port?: ?number,
reporter?: Reporter, reporter?: Reporter,
// deprecated transformCache?: TransformCache,
resetCache?: boolean,
|}; |};
type PrivateMetroOptions = {| type PrivateMetroOptions = {|
@ -86,6 +91,7 @@ async function runMetro({
// $FlowFixMe TODO t0 https://github.com/facebook/flow/issues/183 // $FlowFixMe TODO t0 https://github.com/facebook/flow/issues/183
port = null, port = null,
reporter = new TerminalReporter(new Terminal(process.stdout)), reporter = new TerminalReporter(new Terminal(process.stdout)),
transformCache = TransformCaching.useTempDir(),
watch = false, watch = false,
}: PrivateMetroOptions): Promise<MetroServer> { }: PrivateMetroOptions): Promise<MetroServer> {
const normalizedConfig = config ? Config.normalize(config) : Config.DEFAULT; const normalizedConfig = config ? Config.normalize(config) : Config.DEFAULT;
@ -99,10 +105,6 @@ async function runMetro({
const platforms = const platforms =
(normalizedConfig.getPlatforms && normalizedConfig.getPlatforms()) || []; (normalizedConfig.getPlatforms && normalizedConfig.getPlatforms()) || [];
const transformModulePath = false
? ``
: normalizedConfig.getTransformModulePath();
const providesModuleNodeModules = const providesModuleNodeModules =
typeof normalizedConfig.getProvidesModuleNodeModules === 'function' typeof normalizedConfig.getProvidesModuleNodeModules === 'function'
? normalizedConfig.getProvidesModuleNodeModules() ? normalizedConfig.getProvidesModuleNodeModules()
@ -117,7 +119,6 @@ async function runMetro({
port, port,
projectRoots: finalProjectRoots, projectRoots: finalProjectRoots,
}); });
const serverOptions: ServerOptions = { const serverOptions: ServerOptions = {
assetExts: normalizedConfig.assetTransforms ? [] : assetExts, assetExts: normalizedConfig.assetTransforms ? [] : assetExts,
assetRegistryPath: normalizedConfig.assetRegistryPath, assetRegistryPath: normalizedConfig.assetRegistryPath,
@ -142,8 +143,8 @@ async function runMetro({
sourceExts: normalizedConfig.assetTransforms sourceExts: normalizedConfig.assetTransforms
? sourceExts.concat(assetExts) ? sourceExts.concat(assetExts)
: sourceExts, : sourceExts,
transformCache: TransformCaching.useTempDir(), transformCache,
transformModulePath, transformModulePath: normalizedConfig.getTransformModulePath(),
watch, watch,
workerPath: workerPath:
normalizedConfig.getWorkerPath && normalizedConfig.getWorkerPath(), normalizedConfig.getWorkerPath && normalizedConfig.getWorkerPath(),
@ -157,21 +158,18 @@ type CreateConnectMiddlewareOptions = {|
...PublicMetroOptions, ...PublicMetroOptions,
|}; |};
exports.createConnectMiddleware = async function( exports.createConnectMiddleware = async function({
options: CreateConnectMiddlewareOptions, config,
) { ...rest
}: CreateConnectMiddlewareOptions) {
// $FlowFixMe Flow doesn't support object spread enough for the following line
const metroServer = await runMetro({ const metroServer = await runMetro({
config: options.config, ...rest,
maxWorkers: options.maxWorkers, config,
port: options.port,
reporter: options.reporter,
resetCache: options.resetCache,
watch: true, watch: true,
}); });
const normalizedConfig = options.config const normalizedConfig = config ? Config.normalize(config) : Config.DEFAULT;
? Config.normalize(options.config)
: Config.DEFAULT;
let enhancedMiddleware = metroServer.processRequest; let enhancedMiddleware = metroServer.processRequest;
@ -207,11 +205,18 @@ type RunServerOptions = {|
hmrEnabled?: boolean, hmrEnabled?: boolean,
|}; |};
exports.runServer = async (options: RunServerOptions) => { exports.runServer = async ({
const port = options.port || 8080; host,
const reporter = onReady,
options.reporter || new TerminalReporter(new Terminal(process.stdout)); // $FlowFixMe Flow messes up when using "destructuring"+"default value"+"spread typing"+"stricter field typing" together
port = 8080,
reporter = new TerminalReporter(new Terminal(process.stdout)),
secure = false,
secureKey,
secureCert,
hmrEnabled = false,
...rest
}: RunServerOptions) => {
// Lazy require // Lazy require
const connect = require('connect'); const connect = require('connect');
@ -221,23 +226,22 @@ exports.runServer = async (options: RunServerOptions) => {
attachHmrServer, attachHmrServer,
middleware, middleware,
end, end,
// $FlowFixMe Flow doesn't support object spread enough for the following line
} = await exports.createConnectMiddleware({ } = await exports.createConnectMiddleware({
config: options.config, ...rest,
maxWorkers: options.maxWorkers,
port, port,
reporter, reporter,
resetCache: options.resetCache,
}); });
serverApp.use(middleware); serverApp.use(middleware);
let httpServer; let httpServer;
if (options.secure) { if (secure) {
httpServer = https.createServer( httpServer = https.createServer(
{ {
key: await readFile(options.secureKey), key: await readFile(secureKey),
cert: await readFile(options.secureCert), cert: await readFile(secureCert),
}, },
serverApp, serverApp,
); );
@ -245,12 +249,12 @@ exports.runServer = async (options: RunServerOptions) => {
httpServer = http.createServer(serverApp); httpServer = http.createServer(serverApp);
} }
if (options.hmrEnabled) { if (hmrEnabled) {
attachHmrServer(httpServer); attachHmrServer(httpServer);
} }
httpServer.listen(port, options.host, () => { httpServer.listen(port, host, () => {
options.onReady && options.onReady(httpServer); onReady && onReady(httpServer);
}); });
// Disable any kind of automatic timeout behavior for incoming // Disable any kind of automatic timeout behavior for incoming
@ -294,30 +298,40 @@ type RunBuildOptions = {|
sourceMapUrl?: string, sourceMapUrl?: string,
|}; |};
exports.runBuild = async (options: RunBuildOptions) => { exports.runBuild = async ({
config,
dev = false,
entry,
onBegin,
onComplete,
onProgress,
optimize = false,
output = outputBundle,
out,
platform = `web`,
sourceMap = false,
sourceMapUrl,
...rest
}: RunBuildOptions) => {
// $FlowFixMe Flow doesn't support object spread enough for the following line
const metroServer = await runMetro({ const metroServer = await runMetro({
config: options.config, ...rest,
maxWorkers: options.maxWorkers, config,
resetCache: options.resetCache,
}); });
const output = options.output || outputBundle;
const requestOptions: RequestOptions = { const requestOptions: RequestOptions = {
dev: options.dev, dev,
entryFile: options.entry, entryFile: entry,
inlineSourceMap: options.sourceMap && !!options.sourceMapUrl, inlineSourceMap: sourceMap && !!sourceMapUrl,
minify: options.optimize || false, minify: optimize,
platform: options.platform || `web`, platform,
sourceMapUrl: sourceMapUrl: sourceMap === false ? undefined : sourceMapUrl,
options.sourceMap === false ? undefined : options.sourceMapUrl, createModuleIdFactory: config ? config.createModuleIdFactory : undefined,
createModuleIdFactory: options.config onProgress,
? options.config.createModuleIdFactory
: undefined,
onProgress: options.onProgress,
}; };
if (options.onBegin) { if (onBegin) {
options.onBegin(); onBegin();
} }
let metroBundle; let metroBundle;
@ -328,18 +342,19 @@ exports.runBuild = async (options: RunBuildOptions) => {
await metroServer.end(); await metroServer.end();
} }
if (options.onComplete) { if (onComplete) {
options.onComplete(); onComplete();
} }
const bundleOutput = out.replace(/(\.js)?$/, '.js');
const sourcemapOutput =
sourceMap === false ? undefined : out.replace(/(\.js)?$/, '.map');
const outputOptions: OutputOptions = { const outputOptions: OutputOptions = {
bundleOutput: options.out.replace(/(\.js)?$/, '.js'), bundleOutput,
sourcemapOutput: sourcemapOutput,
options.sourceMap === false dev,
? undefined platform,
: options.out.replace(/(\.js)?$/, '.map'),
dev: options.dev,
platform: options.platform || `web`,
}; };
await output.save(metroBundle, outputOptions, console.log); await output.save(metroBundle, outputOptions, console.log);