본문 바로가기

개발/Front-end

[React Native] React Native Navigation 환경 구축하기 (WebStrorm, Window)


React-Native + react-native-navigation 환경 구축

개발환경

  • WebStorm

  • npm 6.4.1

  • node 10.13.0

  • Android Studio Emulator API 26 x86

Reference

https://wix.github.io/react-native-navigation/#/docs/Installing?id=npm 의 전 과정을 따라합니다.

1. File > New > Project > React Native > Create


2. Terminal > react-native upgrade(안하니까 오류났다)

react-native upgrade 

3. Terminal > react-native-navigation 설치

npm install --save react-native-navigation@alpha

4.Project 폴더 > android > settting.gradle 에 다음 두 줄 추가

  • react-native-navigation 모듈을 추가한다

include ':react-native-navigation'
project(':react-native-navigation').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-navigation/lib/android/app/')


  1. 5. android > gradle > wrapper > gradle-wrapper.properties 의 distributionUrl property 값 확인

distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

와 일치해야하고, 원래 이렇게 되어있어서 따로 수정하진 않았다.

6. android > build.gradle 수정 (app > build.gradle 이 아님에 주의)

자세한 수정 내역은 > https://wix.github.io/react-native-navigation/#/docs/Installing?id=_3-update-androidbuildgradle

아래는 풀코드이다(WebStorm > React Native 환경 구축 기준)

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
   ext {
       buildToolsVersion ="27.0.3"
       minSdkVersion = 19
       compileSdkVersion = 26
       targetSdkVersion = 26
       supportLibVersion = "26.1.0"
  }
   repositories {
       google()
       jcenter()
       mavenLocal()
       mavenCentral()
  }
   dependencies {
       classpath 'com.android.tools.build:gradle:3.0.1'

       // NOTE: Do not place your application dependencies here; they belong
       // in the individual module build.gradle files
  }
}

allprojects {
   repositories {
       mavenCentral()
       google()
       jcenter()
       mavenLocal()
       maven {
           // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
           url "$rootDir/../node_modules/react-native/android"

      }
       maven{
         url 'https://jitpack.io'
        }
  }
}

subprojects { subproject ->
   afterEvaluate {
    project.configurations.all {
           resolutionStrategy.eachDependency { details ->
               if (details.requested.group == 'com.android.support'
                       && !details.requested.name.contains('multidex') ) {
                   details.useVersion "26.1.0"
              }
          }
      }
       if ((subproject.plugins.hasPlugin('android') || subproject.plugins.hasPlugin('android-library'))) {
           android {
               variantFilter { variant ->
                   def names = variant.flavors*.name
                   if (names.contains("reactNative51") || names.contains("reactNative55")) {
                       setIgnore(true)
                  }
              }
          }
      }

  }


}



task wrapper(type: Wrapper) {
   gradleVersion = '4.4'
   distributionUrl = distributionUrl.replace("bin", "all")
}

레퍼런스와 다른 부분은

subprojects { subproject ->
   afterEvaluate {
    project.configurations.all {
           resolutionStrategy.eachDependency { details ->
               if (details.requested.group == 'com.android.support'
                       && !details.requested.name.contains('multidex') ) {
                   details.useVersion "26.1.0"
              }
          }
      }
       if ((subproject.plugins.hasPlugin('android') || subproject.plugins.hasPlugin('android-library'))) {
           android {
               variantFilter { variant ->
                   def names = variant.flavors*.name
                   if (names.contains("reactNative51") || names.contains("reactNative55")) {
                       setIgnore(true)
                  }
              }
          }
      }

  }


}

레퍼런스 최하단에 나와있긴 하지만, 나는 이 두가지 빼먹으면 백이면 백 오류났기 때문에 미리 추가한다.

project.configurations.all 이 부분은

What went wrong: Execution failed for task ':app:preDebugBuild'.

Android dependency 'com.android.support:design' has different version for the compile (25.4.0) and runtime (26.1.0) classpath. You should manually set the same version via DependencyResolution

이런 비스무리한 에러가 발생하지 않도록 설정해주는 부분이다.

그리고, subproject -> afterEvaluate 부분은

Terminal 에서 react-native run-android 를 실행해서 바로 에뮬레이터(또는 디바이스)와 연동되어 실행할 수 있도록 해주는 설정이다. 나는 에뮬레이터를 켜서 개발하기때문에 추가해주었다.


7. android > app > build.gradle(app 폴더 아래!!)

apply plugin: "com.android.application"

import com.android.build.OutputFile

/**
* The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
* and bundleReleaseJsAndAssets).
* These basically call `react-native bundle` with the correct arguments during the Android build
* cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
* bundle directly from the development server. Below you can see all the possible configurations
* and their defaults. If you decide to add a configuration block, make sure to add it before the
* `apply from: "../../node_modules/react-native/react.gradle"` line.
*
* project.ext.react = [
* // the name of the generated asset file containing your JS bundle
* bundleAssetName: "index.android.bundle",
*
* // the entry file for bundle generation
* entryFile: "index.android.js",
*
* // whether to bundle JS and assets in debug mode
* bundleInDebug: false,
*
* // whether to bundle JS and assets in release mode
* bundleInRelease: true,
*
* // whether to bundle JS and assets in another build variant (if configured).
* // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
* // The configuration property can be in the following formats
* // 'bundleIn${productFlavor}${buildType}'
* // 'bundleIn${buildType}'
* // bundleInFreeDebug: true,
* // bundleInPaidRelease: true,
* // bundleInBeta: true,
*
* // whether to disable dev mode in custom build variants (by default only disabled in release)
* // for example: to disable dev mode in the staging build type (if configured)
* devDisabledInStaging: true,
* // The configuration property can be in the following formats
* // 'devDisabledIn${productFlavor}${buildType}'
* // 'devDisabledIn${buildType}'
*
* // the root of your project, i.e. where "package.json" lives
* root: "../../",
*
* // where to put the JS bundle asset in debug mode
* jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
*
* // where to put the JS bundle asset in release mode
* jsBundleDirRelease: "$buildDir/intermediates/assets/release",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in debug mode
* resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in release mode
* resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
*
* // by default the gradle tasks are skipped if none of the JS files or assets change; this means
* // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
* // date; if you have any other folders that you want to ignore for performance reasons (gradle
* // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
* // for example, you might want to remove it from here.
* inputExcludes: ["android/**", "ios/**"],
*
* // override which node gets called and with what additional arguments
* nodeExecutableAndArgs: ["node"],
*
* // supply additional arguments to the packager
* extraPackagerArgs: []
* ]
*/

project.ext.react = [
entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"

/**
* Set this to true to create two separate APKs instead of one:
* - An APK that only works on ARM devices
* - An APK that only works on x86 devices
* The advantage is the size of the APK is reduced by about 4MB.
* Upload all the APKs to the Play Store and people will download
* the correct one based on the CPU architecture of their device.
*/
def enableSeparateBuildPerCPUArchitecture = false

/**
* Run Proguard to shrink the Java bytecode in release builds.
*/
def enableProguardInReleaseBuilds = false

android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion

defaultConfig {
applicationId //project name
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
missingDimensionStrategy "RNN.reactNativeVersion", "reactNative57"
versionCode 1
versionName "1.0"
ndk {
abiFilters "armeabi-v7a", "x86"
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86"
}
}
buildTypes {
release {
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
def versionCodes = ["armeabi-v7a":1, "x86":2]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}

dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
implementation "com.facebook.react:react-native:+" // From node_modules
implementation project(':react-native-navigation')
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}

수정 사항은 레퍼런스 참고(missingDimensionStrategy "RNN.reactNativeVersion", "reactNative57" 은 어차피 레퍼런스 마지막쯤 추가하는거라 미리 해줌)

8. android > gradle.properties에 다음 내용 추가

# Disable incremental resource processing as it broke release build
android.enableAapt2=false


9. android > app > src > main > java > com > <project name> > MainActivity.java 수정

RNN를 통해 View를 구축하도록 java 파일을 수정한다.

MainActivity.java

import com.reactnativenavigation.NavigationActivity;

public class MainActivity extends NavigationActivity{

}

RNN를 통해 View를 구축하도록 java 파일을 수정한다.


10. android > app > src > main > java > com > <project name> > MainApplication.java 수정

MainApplication.java

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

import java.util.Arrays;
import java.util.List;

import com.reactnativenavigation.NavigationApplication;
import com.reactnativenavigation.react.NavigationReactNativeHost;
import com.reactnativenavigation.react.ReactGateway;

public class MainApplication extends NavigationApplication {

   @Override
   protected ReactGateway createReactGateway() {
       ReactNativeHost host = new NavigationReactNativeHost(this, isDebug(), createAdditionalReactPackages()) {
           @Override
           protected String getJSMainModuleName() {
               return "index";
          }
      };
       return new ReactGateway(this, isDebug(), host);
  }

   @Override
   public boolean isDebug() {
       return BuildConfig.DEBUG;
  }

   protected List<ReactPackage> getPackages() {
       // Add additional packages you require here
       // No need to add RnnPackage and MainReactPackage
       return Arrays.<ReactPackage>asList(
           // eg. new VectorIconsPackage()
      );
  }

   @Override
   public List<ReactPackage> createAdditionalReactPackages() {
       return getPackages();
  }
}


    1. 11. Project > index.js 수정

프로젝트 실행 시 가장 먼저 읽는(build 다음) index.js에 Navication을 사용할거라고 알려준다.

index.js

import { Navigation } from "react-native-navigation";
import App from "./App";

Navigation.registerComponent(`navigation.playground.WelcomeScreen`, () => App);

Navigation.events().registerAppLaunchedListener(() => {
   Navigation.setRoot({
       root: {
           component: {
               name: "navigation.playground.WelcomeScreen"
          }
      }
  });
});
Navigation.registerComponent(`navigation.playground.WelcomeScreen`, () => App);

navigation.playground.WelcomeScreen 이 이름으로 App.js 를 등록하고,

        root: {
           component: {
               name: "navigation.playground.WelcomeScreen"
          }
      }

그 화면을 root로 등록한다는 의미이다.

즉, 실행하면 App.js에 구현된 화면이 뜬다.


WebStorm 기준 이와같은 화면이 뜨면 일단 성공!