如何在 React Native 中自动链接依赖项的依赖项?

Shy*_*mov 7 cocoapods react-native

我想与另一个应用程序共享一个应用程序的组件,因此将它们移到一个单独的 NPM 包中。这个包的结构是这样的:

- src
--- components
----- component A
----- component B
- package.json
Run Code Online (Sandbox Code Playgroud)

某些组件使用其他 3rd 方库,它们列在package.json.

现在,当将该共享包安装到第二个项目时,这些 3rd 方依赖项不会自动链接。例如,在调用pod install它们时未安装。

是否有可能以某种方式安装这些 3rd 方依赖项?

小智 1

我们可以如下修补 @react-native-community/cli 中的 findDependencies 函数,以启用依赖项的自动链接依赖关系

function findDependencies(root) {
  let pjson;

  try {
    pjson = JSON.parse(_fs().default.readFileSync(_path().default.join(root, 'package.json'), 'UTF-8'));
  } catch (e) {
    return [];
  }

  const dependencies = Object.keys(pjson.dependencies || []);
  const subDeps = dependencies.reduce(function(accumulator, currentValue) {
    if (!currentValue.includes('your_dependency')) {
      return accumulator;
    }
    const subRoot = `${root}/node_modules/${currentValue}`;
    return accumulator.concat(findDependencies(subRoot));
  }, []);

  const deps = [...Object.keys(pjson.dependencies || {}), ...Object.keys(pjson.devDependencies || {}), ...subDeps];
  return deps;
}
Run Code Online (Sandbox Code Playgroud)