问题
We are using React Native with our existing application.
Due to various reasons, we are downloading a JavaScript bundle from our server and storing it in internal storage.
Now we want React Native AAR to refer to our JavaScript bundle from internal storage instead of the assets folder. For this, somewhere we will need to set a JavaScript bundle directory path, that React Native refers to.
Please let me know how we can achieve this. Is there some kind of property where this path can be set?
回答1:
On android, the bundle file is provided by the ReactNativeHost
.
To provide a custom file, you should:
- Subclass
ReactNativeHost
. The default react native template already does that for you inside MainApplication (themReactNativeHost
member is an anonymous subclass) - Override
getJSBundleFile
with a URI to your file (in internal storage) - Override
getReactNativeHost
inMainApplication
and return your custom host implementation.
Example:
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override protected List<ReactPackage> getPackages() {
return Arrays.asList(new MainReactPackage());
}
@Override protected String getJSMainModuleName() {
return "index";
}
@Nullable @Override protected String getJSBundleFile() {
return "uri://to/your/file"; // <----!!
}
};
@Override public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
回答2:
I found answer to my question after a little research.
In Android, to start react application we need an instance of ReactInstanceManager
. ReactInstanceManagerBuilder
is an builder class for ReactInstanceManager
. ReactInstanceManagerBuilder
has method to set path to JS bundle file.
Please refer below snippet.
ReactInstanceManagerBuilder builder = ReactInstanceManager.builder();
builder.setJSBundleFile("PATH TO YOUR JSBundleFile"); // ex: "assets://index.android.js" or "/sdcard/main.jsbundle"
.
.//other setter calls
.
mReactInstanceManager = builder.build();
mReactRootView.startReactApplication(mReactInstanceManager, appName, arguments);
来源:https://stackoverflow.com/questions/50625098/how-to-change-javascript-bundle-directory-path-from-assets-to-internal-storage-i