首页 > 解决方案 > 如何在 React Native 中自动链接依赖项的依赖项?

问题描述

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

- src
--- components
----- component A
----- component B
- package.json

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

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

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

标签: react-nativecocoapods

解决方案


我们可以在 @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;
}

推荐阅读