# 为rn修改包名[Android篇]

# 通过react-native init myapp命令生成的包名为com.myapp,目标是改为com.rn.app

# 🔧通过编辑器全局搜索myapp,找出相关文件,修改完记得cd android && ./gradlew clean,然后再重新编译


# 一、手动更改

# 1.找到 MainActivity.java | MainApplication.java

android/app/src/main/java/com/myapp/MainActivity.java
android/app/src/main/java/com/myapp/MainApplication.java
1
2

# 2.修改第一行package

package com.rn.app;
1

MainActivity.java getMainComponentName 的返回值需要跟rn注册的名称一致

@Override
protected String getMainComponentName() {
    return "haidaiApp";
}
1
2
3
4

# 3.根据目录层级在com下新建rn文件,rn下新建app文件夹,将两个java文件移入,并删除原有com下app文件夹

调整后结构如下:

android/app/src/main/java/com/rn/app/MainActivity.java
android/app/src/main/java/com/rn/app/MainApplication.java

1
2
3

# 4.修改Android的描述文件android/app/src/main/AndroidManifest.xml的package

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.rn.app">
  ...
</manifest>
1
2
3
4

# 5.修改俩个打包脚本

  • android/app/BUCK

    android_build_config(
        ...
        package = "com.rn.app",
    )
    
    android_resource(
        ...
        package = "com.rn.app",
        ...
    )
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
  • android/app/build.gradle

    defaultConfig {
        applicationId "com.rn.app"
        ...
    }
    
    1
    2
    3
    4

# 6.修改android/settings.gradle

rootProject.name = 'app'
1

# 7.修改app.json

{
  "name": "app",
  "displayName": "haidaiApp",
}
1
2
3
4

# 8.package.json

{
  "name": "app",
}
1
2
3

# 二、自动更改

# 1.全局安装react-native-rename

npm i react-native-rename -g
1

# 2.到项目根目录执行:

react-native-rename "app" -b com.rn.app
1

# 3.然后参照手动更改部分,添加缺少部分