react-native/Libraries/Utilities/HMRClient.js

158 lines
4.9 KiB
JavaScript
Raw Normal View History

/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* 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
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule HMRClient
* @flow
*/
'use strict';
const Platform = require('Platform');
const invariant = require('fbjs/lib/invariant');
/**
* HMR Client that receives from the server HMR updates and propagates them
* runtime to reflects those changes.
*/
const HMRClient = {
enable(platform: string, bundleEntry: string, host: string, port: number) {
invariant(platform, 'Missing required parameter `platform`');
invariant(bundleEntry, 'Missing required paramenter `bundleEntry`');
invariant(host, 'Missing required paramenter `host`');
// need to require WebSocket inside of `enable` function because
Hot Loading E2E basic flow Summary: public Implement all the necessary glue code for several diffs submitted before to get Hot Loading work end to end: - Simplify `HMRClient`: we don't need to make it stateful allowing to enable and disable it because both when we enable and disable the interface we need to reload the bundle. - On the native side we introduced a singleton to process the bundle URL. This new class might alter the url to include the `hot` attribute. I'm not 100% sure this is the best way to implement this but we cannot use `CTLSettings` for this as it's are not available on oss and I didn't want to contaminate `RCTBridge` with something specific to hot loading. Also, we could potentially use this processor for other things in the future. Please let me know if you don't like this approach or you have a better idea :). - Use this processor to alter the default bundle URL and request a `hot` bundle when hot loading is enabled. Also make sure to enable the HMR interface when the client activates it on the dev menu. - Add packager `hot` option. - Include gaeron's `react-transform` on Facebook's JS transformer. The current implementation couples a bit React Native to this feature because `react-transform-hmr` is required on `InitializeJavaScriptAppEngine`. Ideally, the packager should accept an additional list of requires and include them on the bundle among all their dependencies. Note this is not the same as the option `runBeforeMainModule` as that one only adds a require to the provided module but doesn't include all the dependencies that module amy have that the entry point doesn't. I'll address this in a follow up task to enable asap hot loading (9536142) I had to remove 2 `.babelrc` files from `react-proxy` and `react-deep-force-update`. There's an internal task for fixing the underlaying issue to avoid doing this horrible hack (t9515889). Reviewed By: vjeux Differential Revision: D2790806 fb-gh-sync-id: d4b78a2acfa071d6b3accc2e6716ef5611ad4fda
2015-12-29 00:43:21 +00:00
// this module is defined as a `polyfillGlobal`.
// See `InitializeJavascriptAppEngine.js`
const WebSocket = require('WebSocket');
const wsHostPort = port !== null && port !== ''
? `${host}:${port}`
: host;
// Build the websocket url
const wsUrl = `ws://${wsHostPort}/hot?` +
`platform=${platform}&` +
`bundleEntry=${bundleEntry.replace('.bundle', '.js')}`;
const activeWS = new WebSocket(wsUrl);
Hot Loading E2E basic flow Summary: public Implement all the necessary glue code for several diffs submitted before to get Hot Loading work end to end: - Simplify `HMRClient`: we don't need to make it stateful allowing to enable and disable it because both when we enable and disable the interface we need to reload the bundle. - On the native side we introduced a singleton to process the bundle URL. This new class might alter the url to include the `hot` attribute. I'm not 100% sure this is the best way to implement this but we cannot use `CTLSettings` for this as it's are not available on oss and I didn't want to contaminate `RCTBridge` with something specific to hot loading. Also, we could potentially use this processor for other things in the future. Please let me know if you don't like this approach or you have a better idea :). - Use this processor to alter the default bundle URL and request a `hot` bundle when hot loading is enabled. Also make sure to enable the HMR interface when the client activates it on the dev menu. - Add packager `hot` option. - Include gaeron's `react-transform` on Facebook's JS transformer. The current implementation couples a bit React Native to this feature because `react-transform-hmr` is required on `InitializeJavaScriptAppEngine`. Ideally, the packager should accept an additional list of requires and include them on the bundle among all their dependencies. Note this is not the same as the option `runBeforeMainModule` as that one only adds a require to the provided module but doesn't include all the dependencies that module amy have that the entry point doesn't. I'll address this in a follow up task to enable asap hot loading (9536142) I had to remove 2 `.babelrc` files from `react-proxy` and `react-deep-force-update`. There's an internal task for fixing the underlaying issue to avoid doing this horrible hack (t9515889). Reviewed By: vjeux Differential Revision: D2790806 fb-gh-sync-id: d4b78a2acfa071d6b3accc2e6716ef5611ad4fda
2015-12-29 00:43:21 +00:00
activeWS.onerror = (e) => {
let error = (
`Hot loading isn't working because it cannot connect to the development server.
Try the following to fix the issue:
- Ensure that the packager server is running and available on the same network`
);
if (Platform.OS === 'ios') {
error += (
`
- Ensure that the Packager server URL is correctly set in AppDelegate`
);
} else {
error += (
`
- Ensure that your device/emulator is connected to your machine and has USB debugging enabled - run 'adb devices' to see a list of connected devices
- If you're on a physical device connected to the same machine, run 'adb reverse tcp:8081 tcp:8081' to forward requests from your device
- If your device is on the same Wi-Fi network, set 'Debug server host & port for device' in 'Dev settings' to your machine's IP address and the port of the local dev server - e.g. 10.0.1.1:8081`
);
}
error += (
`
URL: ${host}:${port}
Error: ${e.message}`
);
throw new Error(error);
Hot Loading E2E basic flow Summary: public Implement all the necessary glue code for several diffs submitted before to get Hot Loading work end to end: - Simplify `HMRClient`: we don't need to make it stateful allowing to enable and disable it because both when we enable and disable the interface we need to reload the bundle. - On the native side we introduced a singleton to process the bundle URL. This new class might alter the url to include the `hot` attribute. I'm not 100% sure this is the best way to implement this but we cannot use `CTLSettings` for this as it's are not available on oss and I didn't want to contaminate `RCTBridge` with something specific to hot loading. Also, we could potentially use this processor for other things in the future. Please let me know if you don't like this approach or you have a better idea :). - Use this processor to alter the default bundle URL and request a `hot` bundle when hot loading is enabled. Also make sure to enable the HMR interface when the client activates it on the dev menu. - Add packager `hot` option. - Include gaeron's `react-transform` on Facebook's JS transformer. The current implementation couples a bit React Native to this feature because `react-transform-hmr` is required on `InitializeJavaScriptAppEngine`. Ideally, the packager should accept an additional list of requires and include them on the bundle among all their dependencies. Note this is not the same as the option `runBeforeMainModule` as that one only adds a require to the provided module but doesn't include all the dependencies that module amy have that the entry point doesn't. I'll address this in a follow up task to enable asap hot loading (9536142) I had to remove 2 `.babelrc` files from `react-proxy` and `react-deep-force-update`. There's an internal task for fixing the underlaying issue to avoid doing this horrible hack (t9515889). Reviewed By: vjeux Differential Revision: D2790806 fb-gh-sync-id: d4b78a2acfa071d6b3accc2e6716ef5611ad4fda
2015-12-29 00:43:21 +00:00
};
activeWS.onmessage = ({data}) => {
// Moving to top gives errors due to NativeModules not being initialized
const HMRLoadingView = require('HMRLoadingView');
data = JSON.parse(data);
switch (data.type) {
case 'update-start': {
HMRLoadingView.showMessage('Hot Loading...');
break;
}
case 'update': {
const {
modules,
sourceMappingURLs,
sourceURLs,
inverseDependencies,
} = data.body;
if (Platform.OS === 'ios') {
const RCTRedBox = require('NativeModules').RedBox;
RCTRedBox && RCTRedBox.dismiss && RCTRedBox.dismiss();
} else {
const RCTExceptionsManager = require('NativeModules').ExceptionsManager;
RCTExceptionsManager && RCTExceptionsManager.dismissRedbox && RCTExceptionsManager.dismissRedbox();
}
let serverHost;
if (Platform.OS === 'android') {
serverHost = require('NativeModules').AndroidConstants.ServerHost;
} else {
serverHost = port ? `${host}:${port}` : host;
}
modules.forEach(({id, code}, i) => {
code = code + '\n\n' + sourceMappingURLs[i];
require('SourceMapsCache').fetch({
text: code,
url: `http://${serverHost}${sourceURLs[i]}`,
sourceMappingURL: sourceMappingURLs[i],
});
// on JSC we need to inject from native for sourcemaps to work
// (Safari doesn't support `sourceMappingURL` nor any variant when
// evaluating code) but on Chrome we can simply use eval
const injectFunction = typeof global.nativeInjectHMRUpdate === 'function'
? global.nativeInjectHMRUpdate
: eval;
code = [
`__accept(`,
`${id},`,
`function(global,require,module,exports){`,
`${code}`,
'\n},',
`${JSON.stringify(inverseDependencies)}`,
`);`,
].join('');
injectFunction(code, sourceURLs[i]);
});
HMRLoadingView.hide();
break;
}
case 'update-done': {
HMRLoadingView.hide();
break;
}
case 'error': {
HMRLoadingView.hide();
throw new Error(data.body.type + ' ' + data.body.description);
}
default: {
throw new Error(`Unexpected message: ${data}`);
}
}
Hot Loading E2E basic flow Summary: public Implement all the necessary glue code for several diffs submitted before to get Hot Loading work end to end: - Simplify `HMRClient`: we don't need to make it stateful allowing to enable and disable it because both when we enable and disable the interface we need to reload the bundle. - On the native side we introduced a singleton to process the bundle URL. This new class might alter the url to include the `hot` attribute. I'm not 100% sure this is the best way to implement this but we cannot use `CTLSettings` for this as it's are not available on oss and I didn't want to contaminate `RCTBridge` with something specific to hot loading. Also, we could potentially use this processor for other things in the future. Please let me know if you don't like this approach or you have a better idea :). - Use this processor to alter the default bundle URL and request a `hot` bundle when hot loading is enabled. Also make sure to enable the HMR interface when the client activates it on the dev menu. - Add packager `hot` option. - Include gaeron's `react-transform` on Facebook's JS transformer. The current implementation couples a bit React Native to this feature because `react-transform-hmr` is required on `InitializeJavaScriptAppEngine`. Ideally, the packager should accept an additional list of requires and include them on the bundle among all their dependencies. Note this is not the same as the option `runBeforeMainModule` as that one only adds a require to the provided module but doesn't include all the dependencies that module amy have that the entry point doesn't. I'll address this in a follow up task to enable asap hot loading (9536142) I had to remove 2 `.babelrc` files from `react-proxy` and `react-deep-force-update`. There's an internal task for fixing the underlaying issue to avoid doing this horrible hack (t9515889). Reviewed By: vjeux Differential Revision: D2790806 fb-gh-sync-id: d4b78a2acfa071d6b3accc2e6716ef5611ad4fda
2015-12-29 00:43:21 +00:00
};
},
};
module.exports = HMRClient;