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

如何在Expo Web项目中忽略仅原生的react-native-google-mobile-ads模块?

解决Web端打包时忽略react-native-google-mobile-ads包的方案

下面提供几种可行的配置方案,帮你让Web端完全跳过这个原生依赖包:

方案1:用Babel别名替换Web端的包引用

  1. 先安装Babel插件:
npm install --save-dev babel-plugin-module-resolver
  1. 修改项目根目录的babel.config.js,添加针对Web平台的别名规则:
module.exports = function(api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
    plugins: [
      [
        'module-resolver',
        {
          alias: {
            // Web环境下把react-native-google-mobile-ads指向空模块
            'react-native-google-mobile-ads': process.env.EXPO_OS === 'web' ? './emptyModule.js' : 'react-native-google-mobile-ads',
          },
        },
      ],
    ],
  };
};
  1. 在项目根目录新建emptyModule.js,内容如下:
export default {};

方案2:通过Metro配置拦截Web端的包解析

  1. 项目根目录新建或修改metro.config.js:
const { getDefaultConfig } = require('expo/metro-config');

const config = getDefaultConfig(__dirname);

if (process.env.EXPO_OS === 'web') {
  // Web端将react-native-google-mobile-ads映射到空模块
  config.resolver.extraNodeModules = {
    'react-native-google-mobile-ads': require.resolve('./emptyModule.js'),
  };
}

module.exports = config;
  1. 同样需要创建上面提到的emptyModule.js空文件。

方案3:优化代码中的导入逻辑

确保所有涉及该包的导入都放在平台判断的代码块里,避免Web端解析到导入语句:

let MobileAds;
if (Platform.OS !== 'web') {
  // 仅在移动端执行导入
  MobileAds = require('react-native-google-mobile-ads').MobileAds;
}

// 使用广告功能时再做平台校验
if (Platform.OS !== 'web') {
  // 初始化广告、渲染广告组件等逻辑
}

注意事项

  • 所有直接导入react-native-google-mobile-ads的地方都要做平台隔离,不能在全局作用域直接写import,否则Web打包时还是会触发模块解析。
  • 配置完成后,记得清空缓存重启Web服务:
npx expo start --web --clear

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 11:59:54