Skip to content

Commit b9f21dc

Browse files
Jean Lauliacfacebook-github-bot
Jean Lauliac
authored andcommittedNov 6, 2017
react-native: BundleSegments
Reviewed By: davidaurelio Differential Revision: D6231309 fbshipit-source-id: 565cbadedc5fd8ab25025b5846c098f24fb15a82
1 parent 73a01be commit b9f21dc

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
 

‎Libraries/Utilities/BundleSegments.js

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* Copyright (c) 2015-present, Facebook, Inc.
3+
* All rights reserved.
4+
*
5+
* This source code is licensed under the BSD-style license found in the
6+
* LICENSE file in the root directory of this source tree. An additional grant
7+
* of patent rights can be found in the PATENTS file in the same directory.
8+
*
9+
* @flow
10+
* @format
11+
* @providesModule BundleSegments
12+
*/
13+
14+
'use strict';
15+
16+
let segmentLoaders = new Map();
17+
18+
/**
19+
* Ensure that a bundle segment is ready for use, for example requiring some of
20+
* its module. We cache load promises so as to avoid calling `fetchBundle` twice
21+
* for the same bundle. We assume that once a segment is fetched/loaded, it is
22+
* never gettting removed during this instance of the JavaScript VM.
23+
*/
24+
async function loadForModule(moduleID: number): Promise<void> {
25+
const {segmentId} = (require: $FlowFixMe).unpackModuleId(moduleID);
26+
if (segmentId === 0) {
27+
return;
28+
}
29+
let segmentLoader = segmentLoaders.get(segmentId);
30+
if (segmentLoader != null) {
31+
return await segmentLoader;
32+
}
33+
// FIXME: `fetchBundle` should be renamed `fetchSegment`.
34+
const {fetchBundle} = global;
35+
if (fetchBundle == null) {
36+
throw new Error(
37+
'When bundle splitting is enabled, the `global.fetchBundle` function ' +
38+
'must be provided to be able to load particular bundle segments.',
39+
);
40+
}
41+
segmentLoader = new Promise((resolve, reject) => {
42+
fetchBundle(segmentId, error => {
43+
if (error != null) {
44+
reject(error);
45+
return;
46+
}
47+
resolve();
48+
});
49+
});
50+
segmentLoaders.set(segmentId, segmentLoader);
51+
return await segmentLoader;
52+
}
53+
54+
module.exports = {loadForModule};

0 commit comments

Comments
 (0)