react-packager/src/Bundler/index.js: @flow

Reviewed By: davidaurelio

Differential Revision: D4139968

fbshipit-source-id: dc77ea6f0971b5d378883d89290a773205f97c18
This commit is contained in:
Jean Lauliac 2016-11-08 04:46:11 -08:00 committed by Facebook Github Bot
parent c18d46bd03
commit f1aba3f63b
3 changed files with 90 additions and 16 deletions

View File

@ -27,7 +27,7 @@ class BundleBase {
_assets: Array<mixed>; _assets: Array<mixed>;
_finalized: boolean; _finalized: boolean;
_mainModuleId: string | void; _mainModuleId: number | void;
_modules: Array<ModuleTransport>; _modules: Array<ModuleTransport>;
_source: ?string; _source: ?string;
@ -46,7 +46,7 @@ class BundleBase {
return this._mainModuleId; return this._mainModuleId;
} }
setMainModuleId(moduleId: string) { setMainModuleId(moduleId: number) {
this._mainModuleId = moduleId; this._mainModuleId = moduleId;
} }

View File

@ -5,7 +5,10 @@
* This source code is licensed under the BSD-style license found in the * This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant * LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory. * of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/ */
'use strict'; 'use strict';
const Promise = require('promise'); const Promise = require('promise');
@ -23,6 +26,10 @@ const declareOpts = require('../lib/declareOpts');
const imageSize = require('image-size'); const imageSize = require('image-size');
const version = require('../../../../package.json').version; const version = require('../../../../package.json').version;
import AssetServer from '../AssetServer';
import Module from '../node-haste/Module';
import ResolutionResponse from '../node-haste/DependencyGraph/ResolutionResponse';
const sizeOf = Promise.denodeify(imageSize); const sizeOf = Promise.denodeify(imageSize);
const noop = () => {}; const noop = () => {};
@ -102,9 +109,36 @@ const assetPropertyBlacklist = new Set([
'path', 'path',
]); ]);
type Options = {
projectRoots: Array<string>,
blacklistRE: RegExp,
moduleFormat: string,
polyfillModuleNames: Array<string>,
cacheVersion: string,
resetCache: boolean,
transformModulePath: string,
extraNodeModules: {},
nonPersistent: boolean,
assetRoots: Array<string>,
assetExts: Array<string>,
fileWatcher: {},
assetServer: AssetServer,
transformTimeoutInterval: ?number,
allowBundleUpdates: boolean,
};
class Bundler { class Bundler {
constructor(options) { _opts: Options;
_getModuleId: (opts: Module) => number;
_cache: Cache;
_transformer: Transformer;
_resolver: Resolver;
_projectRoots: Array<string>;
_assetServer: AssetServer;
_transformOptionsModule: (path: string, options: {}, bunler: Bundler) => {};
constructor(options: Options) {
const opts = this._opts = validateOpts(options); const opts = this._opts = validateOpts(options);
opts.projectRoots.forEach(verifyRootExists); opts.projectRoots.forEach(verifyRootExists);
@ -128,6 +162,7 @@ class Bundler {
this._getModuleId = createModuleIdFactory(); this._getModuleId = createModuleIdFactory();
if (opts.transformModulePath) { if (opts.transformModulePath) {
/* $FlowFixMe: dynamic requires prevent static typing :'( */
const transformer = require(opts.transformModulePath); const transformer = require(opts.transformModulePath);
if (typeof transformer.cacheKey !== 'undefined') { if (typeof transformer.cacheKey !== 'undefined') {
cacheKeyParts.push(transformer.cacheKey); cacheKeyParts.push(transformer.cacheKey);
@ -166,6 +201,7 @@ class Bundler {
this._assetServer = opts.assetServer; this._assetServer = opts.assetServer;
if (opts.getTransformOptionsModulePath) { if (opts.getTransformOptionsModulePath) {
/* $FlowFixMe: dynamic requires prevent static typing :'( */
this._transformOptionsModule = require( this._transformOptionsModule = require(
opts.getTransformOptionsModulePath opts.getTransformOptionsModulePath
); );
@ -177,7 +213,12 @@ class Bundler {
return this._cache.end(); return this._cache.end();
} }
bundle(options) { bundle(options: {
dev: boolean,
minify: boolean,
unbundle: boolean,
sourceMapUrl: string,
}) {
const {dev, minify, unbundle} = options; const {dev, minify, unbundle} = options;
const moduleSystemDeps = const moduleSystemDeps =
this._resolver.getModuleSystemDependencies({dev, unbundle}); this._resolver.getModuleSystemDependencies({dev, unbundle});
@ -232,7 +273,7 @@ class Bundler {
); );
} }
hmrBundle(options, host, port) { hmrBundle(options: {platform: mixed}, host: string, port: number) {
return this._bundle({ return this._bundle({
...options, ...options,
bundle: new HMRBundle({ bundle: new HMRBundle({
@ -265,7 +306,7 @@ class Bundler {
assetPlugins, assetPlugins,
onProgress, onProgress,
}) { }) {
const onResolutionResponse = response => { const onResolutionResponse = (response: ResolutionResponse) => {
bundle.setMainModuleId(response.getModuleId(getMainModule(response))); bundle.setMainModuleId(response.getModuleId(getMainModule(response)));
if (entryModuleOnly) { if (entryModuleOnly) {
response.dependencies = response.dependencies.filter(module => response.dependencies = response.dependencies.filter(module =>
@ -275,7 +316,12 @@ class Bundler {
response.dependencies = moduleSystemDeps.concat(response.dependencies); response.dependencies = moduleSystemDeps.concat(response.dependencies);
} }
}; };
const finalizeBundle = ({bundle, transformedModules, response, modulesByName}) => const finalizeBundle = ({bundle, transformedModules, response, modulesByName}: {
bundle: Bundle,
transformedModules: Array<{module: Module, transformed: {}}>,
response: ResolutionResponse,
modulesByName: {[name: string]: Module},
}) =>
Promise.all( Promise.all(
transformedModules.map(({module, transformed}) => transformedModules.map(({module, transformed}) =>
bundle.addModule(this._resolver, response, module, transformed) bundle.addModule(this._resolver, response, module, transformed)
@ -330,7 +376,7 @@ class Bundler {
onModuleTransformed = noop, onModuleTransformed = noop,
finalizeBundle = noop, finalizeBundle = noop,
onProgress = noop, onProgress = noop,
}) { }: *) {
const transformingFilesLogEntry = const transformingFilesLogEntry =
print(log(createActionStartEntry({ print(log(createActionStartEntry({
action_name: 'Transforming files', action_name: 'Transforming files',
@ -401,7 +447,7 @@ class Bundler {
}); });
} }
invalidateFile(filePath) { invalidateFile(filePath: string) {
this._cache.invalidate(filePath); this._cache.invalidate(filePath);
} }
@ -412,6 +458,13 @@ class Bundler {
minify = !dev, minify = !dev,
hot = false, hot = false,
generateSourceMaps = false, generateSourceMaps = false,
}: {
entryFile: string,
platform: mixed,
dev?: boolean,
minify?: boolean,
hot?: boolean,
generateSourceMaps?: boolean,
}) { }) {
return this.getTransformOptions( return this.getTransformOptions(
entryFile, entryFile,
@ -434,11 +487,11 @@ class Bundler {
}); });
} }
stat(filePath) { stat(filePath: string) {
return this._resolver.stat(filePath); return this._resolver.stat(filePath);
} }
getModuleForPath(entryFile) { getModuleForPath(entryFile: string) {
return this._resolver.getModuleForPath(entryFile); return this._resolver.getModuleForPath(entryFile);
} }
@ -452,6 +505,16 @@ class Bundler {
generateSourceMaps = false, generateSourceMaps = false,
isolateModuleIDs = false, isolateModuleIDs = false,
onProgress, onProgress,
}: {
entryFile: string,
platform: mixed,
dev?: boolean,
minify?: boolean,
hot?: boolean,
recursive?: boolean,
generateSourceMaps?: boolean,
isolateModuleIDs?: boolean,
onProgress?: () => mixed,
}) { }) {
return this.getTransformOptions( return this.getTransformOptions(
entryFile, entryFile,
@ -480,7 +543,11 @@ class Bundler {
}); });
} }
getOrderedDependencyPaths({ entryFile, dev, platform }) { getOrderedDependencyPaths({ entryFile, dev, platform }: {
entryFile: string,
dev: boolean,
platform: mixed,
}) {
return this.getDependencies({entryFile, dev, platform}).then( return this.getDependencies({entryFile, dev, platform}).then(
({ dependencies }) => { ({ dependencies }) => {
const ret = []; const ret = [];
@ -592,7 +659,7 @@ class Bundler {
}); });
} }
_generateAssetObjAndCode(module, assetPlugins, platform = null) { _generateAssetObjAndCode(module, assetPlugins, platform: mixed = null) {
const relPath = getPathRelativeToRoot(this._projectRoots, module.path); const relPath = getPathRelativeToRoot(this._projectRoots, module.path);
var assetUrlPath = path.join('/assets', path.dirname(relPath)); var assetUrlPath = path.join('/assets', path.dirname(relPath));
@ -649,6 +716,7 @@ class Bundler {
} }
let [currentAssetPlugin, ...remainingAssetPlugins] = assetPlugins; let [currentAssetPlugin, ...remainingAssetPlugins] = assetPlugins;
/* $FlowFixMe: dynamic requires prevent static typing :'( */
let assetPluginFunction = require(currentAssetPlugin); let assetPluginFunction = require(currentAssetPlugin);
let result = assetPluginFunction(asset); let result = assetPluginFunction(asset);
@ -663,7 +731,13 @@ class Bundler {
} }
} }
_generateAssetModule(bundle, module, moduleId, assetPlugins = [], platform = null) { _generateAssetModule(
bundle,
module,
moduleId,
assetPlugins: Array<string> = [],
platform: mixed = null,
) {
return Promise.all([ return Promise.all([
module.getName(), module.getName(),
this._generateAssetObjAndCode(module, assetPlugins, platform), this._generateAssetObjAndCode(module, assetPlugins, platform),
@ -681,7 +755,7 @@ class Bundler {
}); });
} }
getTransformOptions(mainModuleName, options) { getTransformOptions(mainModuleName: string, options: {}) {
const extraOptions = this._transformOptionsModule const extraOptions = this._transformOptionsModule
? this._transformOptionsModule(mainModuleName, options, this) ? this._transformOptionsModule(mainModuleName, options, this)
: null; : null;

View File

@ -49,7 +49,7 @@ class Cache {
}: { }: {
resetCache: boolean, resetCache: boolean,
cacheKey: string, cacheKey: string,
cacheDirectory: string, cacheDirectory?: string,
}) { }) {
this._cacheFilePath = Cache.getCacheFilePath(cacheDirectory, cacheKey); this._cacheFilePath = Cache.getCacheFilePath(cacheDirectory, cacheKey);
if (!resetCache) { if (!resetCache) {