Amplify React Native - Duplicate Error с помощью ampify add api - PullRequest
2 голосов
/ 25 марта 2020

Я использую это руководство по усилению https://aws-amplify.github.io/docs/js/tutorials/building-react-native-apps/#connect -to-your-backend-1 , и когда я создаю API с помощью "aplify add api", приложение завершается ошибкой. Я использую "expo" и использую IphoneX для фазы тестирования.

Код моего приложения

import React, { Component } from 'react';
import { StyleSheet, Text, Button, View, Alert } from 'react-native';
import Amplify, { API } from 'aws-amplify';
import amplify from './aws-exports';
import awsmobile from './aws-exports';
import { withAuthenticator } from 'aws-amplify-react-native';

Amplify.configure(amplify);
Amplify.configure(awsmobile);

state = { apiResponse: null };

class App extends Component {


  async getSample() {
    const path = "/items"; // you can specify the path
     const apiResponse = await API.get("theListApi" , path); //replace the API name
     console.log('response:' + apiResponse);
     this.setState({ apiResponse });
   }


  render() { 
    return (
      <View style={styles.container}>
      <Text>test</Text>

      <Button title="Send Request" onPress={this.getSample.bind(this)} />
    <Text>Response: {this.state.apiResponse && JSON.stringify(this.state.apiResponse)}</Text>

    </View>
    );
  }
}

export default withAuthenticator(App);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#63C8F1',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

при выполнении "expo start" командная строка возвращает сообщение об ошибке:

jest-haste-map: Haste module naming collision: theListFunction
  The following files share their name; please adjust your hasteImpl:
    * <rootDir>/amplify/backend/function/theListFunction/src/package.json
    * <rootDir>/amplify/#current-cloud-backend/function/theListFunction/src/package.json


Failed to construct transformer:  DuplicateError: Duplicated files or mocks. Please check the console for more info
    at setModule (/Users/j_hen/Documents/jdev/smartApp/sourcecode/mySmaertProject/node_modules/jest-haste-map/build/index.js:620:17)
    at workerReply (/Users/j_hen/Documents/jdev/smartApp/sourcecode/mySmaertProject/node_modules/jest-haste-map/build/index.js:691:9)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Promise.all (index 391) {
  mockPath1: 'amplify/backend/function/theListFunction/src/package.json',
  mockPath2: 'amplify/#current-cloud-backend/function/theListFunction/src/package.json'
}
(node:1506) UnhandledPromiseRejectionWarning: Error: Duplicated files or mocks. Please check the console for more info
    at setModule (/Users/j_hen/Documents/jdev/smartApp/sourcecode/mySmaertProject/node_modules/jest-haste-map/build/index.js:620:17)
    at workerReply (/Users/j_hen/Documents/jdev/smartApp/sourcecode/mySmaertProject/node_modules/jest-haste-map/build/index.js:691:9)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Promise.all (index 391)
(node:1506) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1506) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

или

Error: Duplicated files or mocks. Please check the console for more info
    at setModule (/Users/j_hen/Documents/jdev/smartApp/sourcecode/mySmaertProject/node_modules/jest-haste-map/build/index.js:620:17)
    at workerReply (/Users/j_hen/Documents/jdev/smartApp/sourcecode/mySmaertProject/node_modules/jest-haste-map/build/index.js:691:9)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Promise.all (index 391)

Что не так? Как правильно использовать API?

Ответы [ 2 ]

2 голосов
/ 28 марта 2020

Amplify создает копию вашей текущей конфигурации облачного бэкэнда в amplify/#current-cloud-backend/.

Вам не нужны эти файлы для сборки вашего приложения, поэтому вы можете игнорировать их, чтобы избавиться от ошибки.

Для этого вы можете создать черный список и добавить в него папку. Создайте файл rn-cli.config.js в root вашего проекта.

./rn-cli.config.js:

const blacklist = require('metro').createBlacklist;

module.exports = {
  resolver: {
    blacklistRE: blacklist([/#current-cloud-backend\/.*/]),
  },
};

Ссылочная проблема .

0 голосов
/ 30 марта 2020

Если вы используете машинопись, вы должны создать черный список на metro.config.js НЕ rn-cli.config.js.

module.exports = {
  resolver: {
    blacklistRE: /#current-cloud-backend\/.*/
  },
  transformer: {
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: false,
        inlineRequires: false,
      },
    }),
  },
};

Как указано здесь .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...