Original link: motalks.cn/2016/10/26/… Please indicate the source of reprint.
Since the company’s Desktop computer of Win 7 system has good performance, I went through the process of building React Native development environment and integrating React Native into the existing Android project on Windows system again. There is little difference between the Mac and Windows system in integrating React Native. Most of the problems are in the environment construction. I will write about the Environment construction of React Native under Windows. One last piece of advice, please buy Mac Book Pro directly on the top, are tears.
Initialize React Native in an existing project
Run the following three commands in the project root directory to initialize the React Native process.
npm init
npm install --save react react-native
curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfigCopy the code
Here is a step-by-step explanation of each command:
About the NPM init command
This step generates a package.json file in the project root directory. This is mainly project information, here will generate the “scripts” field needed for the next step, I forgot the screenshots of my own process, used sky OO7 image.
Next, add the following sentence under the scripts field in the package.json file, and delete “test” :”no” as well. Set the path of the “start” command.
"start": "node node_modules/react-native/local-cli/cli.js start"Copy the code
Install –save react react-native
Initialize React and React Native files. After installing React, you will see the node_modules folder in the root directory of the project.
About curl Command
Curl is an open source file transfer tool that works on the command line using URL syntax. It is widely used in Unix, various Linux distributions, and has ports for DOS and Win32 and Win64.
Since Mac OS is based on the Unix kernel, this command will happily execute on the Mac if the network is clear and will generate a.flowconfig file in your project root directory.
On Windows you’ll be desperate to see a command line that says “‘ curl’ is not an internal or external command, nor is it a runnable program or batch file.” You can according to the Windows installation using the curl command tutorial to use this command, also can be directly under the root directory of the project. A new flowconfig file, then raw.githubusercontent.com/facebook/re… Copy the contents of the For the convenience of students with poor network, the configuration information of this webpage has been copied in the following (the configuration information will be updated at any time, it is recommended to get the real-time configuration information from the website).
[ignore] # We fork some components by platform. .*/*[.]android.js # Ignore templates with `@flow` in header .*/local-cli/generator.* # Ignore malformed json .*/node_modules/y18n/test/.*\.json # Ignore the website subdir <PROJECT_ROOT>/website/.* # Ignore BUCK generated dirs <PROJECT_ROOT>/\.buckd/ # Ignore unexpected extra @providesModule .*/node_modules/commoner/test/source/widget/share.js # Ignore duplicate module providers # For RN Apps installed via npm, "Libraries" folder is inside node_modules/react-native but in the source repo it is in the root .*/Libraries/react-native/React.js .*/Libraries/react-native/ReactNative.js .*/node_modules/jest-runtime/build/__tests__/.* [include] [libs] Libraries/react-native/react-native-interface.js flow/ [options] module.system=haste esproposal.class_static_fields=enable esproposal.class_instance_fields=enable experimental.strict_type_args=true munge_underscores=true module.name_mapper='^image! [a-zA-Z0-9$_-]+Copy the code
Add the index.android.js file to the project root directory
Create an index.android.js file in the root directory and copy the following contents.
'use strict';
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class HelloWorld extends React.Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.hello}>Hello, World</Text>
</View>)}}var styles = StyleSheet.create({
container: {
flex: 1.justifyContent: 'center',},hello: {
fontSize: 20.textAlign: 'center'.margin: 10,}}); AppRegistry.registerComponent('HelloWorld', () => HelloWorld);Copy the code
Configurations related to existing projects
Module level build.gradle configuration changes
Add the React Native dependency to the build.gradle file in your app folder (Gradle at module level).
dependencies {
compile "com.facebook.react:react-native:+" // From node_modules.
}Copy the code
The “+” sign here indicates the latest React Native version. You can also specify a specific version number.
Build. gradle configuration changes at project level
Add it to the build.gradle file (gradle at the project level) in your project root directory
allprojects {
repositories {
jcenter()
maven {
// All of React Native (JS, Android binaries) is installed from npm
url "$rootDir/.. /node_modules/react-native/android"}}}Copy the code
The important thing to note here is that it is added under the AllProjects node. This is because the Android project’s default dependency package source jCenter () does not include the latest React Native (it only goes up to 0.20.1). New versions of React Native are available only in NPM, so you’ll need to add a source of dependencies. After compiling, check the React-native version of the External Libraries. If the value is 0.20.1, the maven dependency source is not added successfully. Change the url path to “$rootDir/node_modules/react-native/ Android “. The latest version currently available should be 0.35.0.
Adding native code
Notes: Starting with version 0.29.0, mReactInstanceManager calls onHostResume(), onHostPause() in the lifecycle methods onResume(), onPause(). MReactInstanceManager still calls onResume(), however, ReactInstanceManager has changed to onHostResume(), So calling onResume() will return a red. Everything else is in the comments.
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import com.facebook.react.BuildConfig;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;
/** * Created by silencelin on 2016/10/24. */
public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler {
private ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactRootView = new ReactRootView(this);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new MainReactPackage())
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
/ / startReactApplication moduleName parameters the method must be with you in the index. The android. Js file / / AppRegistry registerComponent registration is consistent with the project name
mReactRootView.startReactApplication(mReactInstanceManager, "AwesomeProject".null);
setContentView(mReactRootView);
}
@Override
public void invokeDefaultOnBackPressed(a) {
super.onBackPressed();
}
@Override
protected void onResume(a) {
super.onResume();
if(mReactInstanceManager ! =null) {
mReactInstanceManager.onHostResume(this.this); }}@Override
protected void onPause(a) {
super.onPause();
if(mReactInstanceManager ! =null) { mReactInstanceManager.onHostPause(); }}@Override
protected void onDestroy(a) {
super.onDestroy();
if(mReactInstanceManager ! =null) { mReactInstanceManager.onHostDestroy(); }}@Override
public void onBackPressed(a) {
if(mReactInstanceManager ! =null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed(); }}@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager ! =null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event); }}Copy the code
Next, don’t forget to register in androidmanifest.xml.
<activity
android:name=".MyReactActivity"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />Copy the code
DevSettingsActivity is the following Settings page, which must be used during development.
There are network permissions, general projects will have this permission.
<uses-permission android:name="android.permission.INTERNET" />Copy the code
There is another permission, which is not mentioned in official documents and many other articles, that the old driver is going to start the bus, so sit tight. You can’t even bring up the Settings menu above by shaking your kirin arm without applying for the hover window permission.
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>Copy the code
Run your App!
Finally, at this exciting moment, type the following command in your project root directory
npm startCopy the code
About the NPM start command
This command executes the value of “start” under “scripts” in package.json.
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start"
}Copy the code
See clientry.js file, and finally execute clientry.js script, a bunch of configuration parameters, simply say to configure a local Web server environment. (nodeJs really does not understand, if there is an error, please correct.)
Success looks like this:
Tips for Running Your App
Then, as usual, click the Android Run button to deploy the project to a virtual machine or real machine. Note that debug is selected for build mode. If you accidentally select release mode, you will get this error:
Could not get BatchedBridge, make sure your bundle is packaged correctly
Because the official version requires you to create the React Native bundle and store it in the local implies directory. Run the following command:
react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/com/your-company-name/app-package-name/src/main/assets/index.android.bundle --assets-dest android/com/your-company-name/app-package-name/src/main/res/Copy the code
Note that replace android/com/your-company-name/app-package-name/ SRC /main with the actual path of your project. Last see asserts generated in the directory index. The android. The bundle and index android. Bundle. The meta two files means that the above command execution is successful, can be happy to run your program.
React Native code debugging differs between the debug build and release build modes
Debug build: After changing the JS code, you can simply shake it and select Reload JS to see the updated effect.
Release build: after the js code is modified, you need to re-generate the index.android.bundle file to see the updated effect. Because you can’t rely on local servers to update index.android.bundle after the official release. So this raises the question of how React Native will be hot updated.
Next arrangement
React Native Android development environment
React Native integration with existing Android projects
React Native Project Hot Update (to be updated)
React Native optimizations (package size optimizations, preloading solutions, white screens, etc.)