【问题标题】:Error: While trying to resolve module @apollo/client React Native错误:尝试解析模块 @apollo/client React Native 时
【发布时间】:2022-01-17 03:15:04
【问题描述】:

安装新版本的 apollo 客户端后出现此错误。我尝试了其他版本并降级但没有。我还尝试在 metro.config.js 中指定解析“cjs”类型的文件(@apollo/client/main.cjs),但没有。

错误

error: Error: While trying to resolve module `@apollo/client` from file `****\src\api\queries\home.js`, the package `****\node_modules\@apollo\client\package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`****\node_modules\@apollo\client\main.cjs`. Indeed, none of these files exist:

依赖关系

"@apollo/client": "^3.3.2",
"graphql": "^15.4.0",

有人可以帮帮我吗?将不胜感激!

【问题讨论】:

    标签: react-native graphql bundle apollo-client


    【解决方案1】:

    只需将 cjs 文件扩展名添加到 metro.config.js 即可。

    根据博览会官方Adding more file extensions to assetExts文档...

    const { getDefaultConfig } = require('@expo/metro-config');
    
    const defaultConfig = getDefaultConfig(__dirname);
    
    defaultConfig.resolver.assetExts.push('cjs');
    
    module.exports = defaultConfig;
    

    【讨论】:

      【解决方案2】:

      我在 react-native 中遇到了完全相同的问题。 从文档中可以看出,您需要添加处理“cjs”文件的能力。

      https://github.com/apollographql/apollo-client/blob/main/CHANGELOG.md#apollo-client-354-2021-11-19

      今天通过添加到 node_modules/metro-config/src/defaults/defaults.js 解决了这个问题

      export.sourceExts = ["js", "json", "ts", "tsx", "cjs"];

      从项目文件夹中 对于安卓:

      cd android && ./gradlew clean

      对于 xcode 中的 ios :

      清理 -> 运行

      【讨论】:

        【解决方案3】:

        https://github.com/apollographql/apollo-client/blob/main/CHANGELOG.md#apollo-client-354-2021-11-19 所述,解决方案应该是添加

        const { getDefaultConfig } = require("metro-config");
        const { resolver: defaultResolver } = getDefaultConfig.getDefaultValues();
        exports.resolver = {
          ...defaultResolver,
          sourceExts: [
            ...defaultResolver.sourceExts,
            "cjs",
          ],
        };
        

        在你的metro.config.js

        在我的例子中,我已经默认生成了一个module.exports,所以我只需要制作这个文件:

        const {getDefaultConfig} = require('metro-config');
        const {resolver: defaultResolver} = getDefaultConfig.getDefaultValues();
        
        module.exports = {
          transformer: {
            getTransformOptions: async () => ({
              transform: {
                experimentalImportSupport: false,
                inlineRequires: true,
              },
            }),
          },
          resolver: {
            ...defaultResolver,
            sourceExts: [...defaultResolver.sourceExts, 'cjs'],
          },
        };
        
        

        【讨论】:

          猜你喜欢
          • 2023-02-25
          • 1970-01-01
          • 2019-04-15
          • 2021-02-05
          • 2022-10-21
          • 1970-01-01
          • 2019-08-09
          • 2019-07-06
          • 2017-06-06
          相关资源
          最近更新 更多