在构建时使用 Create React Native App 和 Expo 在 React Native 中自定义代码

Customizing code at build-time in React Native with Create React Native App and Expo

一般来说,有没有办法在构建步骤中自定义应用程序代码?

具体而言,通常需要从应用程序向本地后端发出请求 ([1], [2], , [4])。

使用 Webpack 可以通过 DefinePlugin 将占位符替换为正在构建的机器的 IP 地址来解决这种情况。

我们最终使用了受 Webpack 的 react-native-typescript-transformer or react-native-sass-transformer. It's idea is pretty much equivalent to the mentioned DefinePlugin 等转换器启发的有点老套的方法。

首先,工程目录下的一些transformer文件(随便命名,更新引用即可):

configBuildReplacements.js

// whatever logic you need

module.exports = {
    API_HOST_PLACEHOLDER: `http://${getLocalNetworkAddress()}:3000`,
    SOME_OTHER_DYNAMIC_VALUE: someFun(),
}

configBuildReplaceTransformer.js

const semver = require('semver')    

let upstreamTransformer = null

const reactNativeVersionString = require('react-native/package.json').version
const reactNativeMinorVersion = semver(reactNativeVersionString).minor

if (reactNativeMinorVersion >= 56) {
    upstreamTransformer = require('metro/src/reactNativeTransformer')
}
else if (reactNativeMinorVersion >= 52) {
    upstreamTransformer = require('metro/src/transformer')
}
else if (reactNativeMinorVersion >= 47) {
    upstreamTransformer = require('metro-bundler/src/transformer')
}
else if (reactNativeMinorVersion === 46) {
    upstreamTransformer = require('metro-bundler/build/transformer')
}
else {
    // handle RN <= 0.45
    const oldUpstreamTransformer = require('react-native/packager/transformer')
    upstreamTransformer = {
        transform({ src, filename, options }) {
            return oldUpstreamTransformer.transform(src, filename, options)
        },
    }
}


module.exports.transform = function (src, filename, options) {
    // handle RN >= 0.46
    if (typeof src === 'object') {
        ({ src, filename, options } = src)
    }

    const replacements = require('./configBuildReplacements')

    const modifiedSrc = Object.keys(replacements).reduce(
        (src, replacementKey) => src.replace(
            new RegExp(replacementKey, 'g'),
            replacements[replacementKey],
        ),
        src,
    )

    return upstreamTransformer.transform({
        src: modifiedSrc,
        filename,
        options,
    })
}

导出的transform函数使用之前文件configBuildReplacements.js导出的对象作为字典,在将此代码交给默认(上游)之前,将源代码中的键子字符串替换为值子字符串变压器.

并将这个新变压器连接到项目:

  • 使用 Expo,将 transformer 打包程序选项添加到 app.json:

    {
      "expo": {
        "packagerOpts": {
          "transformer": "configBuildReplaceTransformer.js"
        }
      }
    }
    
  • 没有 Expo,将 getTransformModulePath() 添加到 rn-cli.config.js(这是 React Native CLI 的可选配置文件的默认路径,在这篇文章):

    module.exports = {
        getTransformModulePath() {
            return require.resolve('./configBuildReplaceTransformer')
        },        
    }
    

完成后,和DefinePlugin一样,代码如

get('API_HOST_PLACEHOLDER/info')

会变成

get('http://192.168.42.23:3000/info')