react-native - 将本地包作为不在 React-Native 项目中的模块导入

标签 react-native webpack lerna

在 React-Native 项目中,我发现如果您的本地包有一个有效的 package.json 文件,您可以像 node_modules 中的模块一样导入该文件,而无需使用相对路径。

例如,

app/                             # a React-Native project
  |- any_folder_for_packages/
  |   |- foo/
  |       |- package.json
  |       |- index.js
  |- src/
  |   |- bar/
  |       |- bar.js
  |- ...

在这种情况下,您可以使用以下任一方法在 bar.js 中导入包 foo:

// with a relative path
import foo from '../../any_folder_for_packages/foo';

// like a module (without a relative path)
import foo from 'foo';

打包器将尝试查找并使用任何包含符合要求的 package.json 的本地模块。

问题

我有一个本地包,不在React-Native项目中,如何导入它

projects/
  |- app/                # a React-Native project
  |   |- src/
  |   |   |- bar/
  |   |       |- bar.js  # need to import the package foo as a module which is not in this project
  |   |- ...
  |- other_paths/
      |- foo/
          |- package.json
          |- index.js

我尝试使用

// like a module (without a relative path)
import foo from 'foo';

但未能找到该模块。

在打包开发或捆绑生产时如何使用 react-native 查找包?

最佳答案

@Plague 给出的答案在 native react 中不起作用。您必须配置 Metro.config.js 文件才能使用本地包。

如果使用 Expo

在expo中,metro.config.js文件可能不可见,因此在项目的根目录中,运行此命令;

npx expo customize metro.config.js

这将为您生成具有一些默认配置的文件。现在要导入任何包,您必须在这里修改两件事;

config.resolver.nodeModulesPaths,包含该包,并且; config.watchFolders 来监视包。

简而言之,metro.config.js 文件应该是这样的;

// Learn more https://docs.expo.io/guides/customizing-metro
const { getDefaultConfig } = require("expo/metro-config");

const config = getDefaultConfig(__dirname);

const packagePath = "/full/path/to/package";

// here i added the packagePath to the list in the configuration to include it    
config.resolver.nodeModulesPaths.push(packagePath);

// here i added the package again to another configuration key, to keep a watch on it if we make any changes.
config.watchFolders.push(packagePath);

module.exports = config;

就是这样,但是您的代码编辑器可能会报告找不到模块,要删除该警告,您只需运行下面的命令即可;

npm install /path/to/package

但这有一个问题

我们的包中的依赖项与主项目的依赖项冲突。

所以这是安装本地包的另一种方法。

使用本地安装

为此,我们不需要对任何文件进行任何更改。我们只需要安装这个包即可;

npm install install-local

然后使用这个安装本地包;

npx install-local --save path/to/package

关于react-native - 将本地包作为不在 React-Native 项目中的模块导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45695904/

相关文章:

android - createMaterialTopTabNavigator 在一次导航后不导航

javascript - typescript - 引用错误 : exports is not defined

reactjs - 语法错误 : Support for the experimental syntax 'jsx' isn't currently enabled

android - react native : Fetch requests are not working with remote debugger active (Android)

javascript - (React Native)设置 AsyncStorage 值,但在检索它时收到垃圾

node.js - 使用 mocha 运行时,仍然收到 babel-plugin-syntax-dynamic-import 动态导入的语法错误

url - 参数中的 Vue Router Webpack Dot

javascript - 如何屏蔽 Lerna 包的内部结构,使其他包无法导入它们?

typescript - 在 VSCode 中调试 lerna-typescript 项目

yarnpkg - Yarn workspace + lerna 在每个子包中创建 node_modules