You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需Eject Expo(Android)项目创建libs文件夹的方法

在Expo Managed Workflow中无需Eject创建Android libs文件夹并集成AAR文件

完全可以通过扩展你的Expo Config Plugin来实现,核心思路是在Expo构建Android项目的临时目录中,动态创建libs文件夹并复制你的AAR文件过去,具体步骤如下:

1. 准备本地资源与插件文件

  • 在项目根目录创建assets/aars文件夹,将需要集成的.aar文件放入其中。
  • 新建一个本地Config Plugin文件,比如withAndroidLibsSetup.js,写入以下逻辑:
const { withProjectBuildGradle, withDangerousMod } = require('@expo/config-plugins');
const fs = require('fs');
const path = require('path');

module.exports = function withAndroidLibs(config) {
  // 动态创建libs目录并复制AAR文件
  config = withDangerousMod(config, [
    'android',
    async (config) => {
      // 获取构建时生成的临时Android项目根目录
      const androidProjectDir = config.modRequest.platformProjectRoot;
      const libsDirPath = path.join(androidProjectDir, 'libs');
      // 本地AAR文件的路径
      const localAarPath = path.join(config.projectRoot, 'assets', 'aars', 'your-sdk-file.aar');

      // 创建libs目录(如果不存在)
      if (!fs.existsSync(libsDirPath)) {
        fs.mkdirSync(libsDirPath, { recursive: true });
      }

      // 复制AAR到目标目录
      if (fs.existsSync(localAarPath)) {
        fs.copyFileSync(localAarPath, path.join(libsDirPath, 'your-sdk-file.aar'));
      } else {
        throw new Error(`未找到指定的AAR文件,请检查路径:${localAarPath}`);
      }

      return config;
    },
  ]);

  // 给build.gradle添加AAR依赖(如果还没配置)
  config = withProjectBuildGradle(config, (config) => {
    if (config.modResults.language === 'groovy') {
      config.modResults.contents = config.modResults.contents.replace(
        'dependencies {',
        `dependencies {
    implementation files('libs/your-sdk-file.aar')`
      );
    } else {
      // 适配Kotlin DSL格式的build.gradle
      config.modResults.contents = config.modResults.contents.replace(
        'dependencies {',
        `dependencies {
    implementation(files("libs/your-sdk-file.aar"))`
      );
    }
    return config;
  });

  return config;
};

2. 配置插件到项目

打开app.json或app.config.js,在expo.plugins数组中添加这个本地插件:

{
  "expo": {
    // ...其他配置
    "plugins": [
      "./withAndroidLibsSetup.js"
    ]
  }
}

3. 测试构建

运行eas build --platform android或者expo run:android(需本地Android开发环境),Expo会在构建流程中自动创建libs文件夹并复制AAR文件,同时修改build.gradle引入依赖,全程无需Eject。

注意事项

  • 替换代码中的your-sdk-file.aar为你实际的AAR文件名,如果有多个AAR文件,可以循环遍历assets/aars目录下的文件进行复制。
  • 确保assets/aars目录未被.gitignore或eas.json的构建上下文排除,否则EAS Build会找不到AAR文件。

内容的提问来源于stack exchange,提问作者haobei620

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 11:52:20