当使用react-native init创建新项目后,在根目录下有一个index.js的入口文件:
import {AppRegistry} from 'react-native';
import App from './src/App';
import {name as appName} from './app.json';
AppRegistry.registerComponent(appName, () => App);
在其中定义了这个react-native项目的入口,默认情况下,当我们运行react-native start来启动metro server时,这个index.js也是这个web服务的入口,那么在native端是如何体现的呢?
在AppDelegate.m文件中有这样一段代码:
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}
debug模式下index所指向的就是根目录下的index.js,若将根目录下的index.js换到一个新的目录,例如,在根目录下新建一个demo目录,并将index.js移动至该目录下。再次运行react-native start,会发现模拟器报错,找不到入口。
解决的方式也很简单,仅需要将@"index"这个参数改为新的index目录即可,即demo或demo/index。同理对于Android,也是需要修改MainApplication.java中类似的路径:
...
@Override
protected String getJSMainModuleName() {
return "index";
}
...
对于product模式则无影响,在打包jsbundle时,传入的参数中有一个entry,只需要将其指定于新的路径即可。