接到“无效电话"将要求与 Typescript 和 Expo 一起使用时 [英] Getting "Invalid call" when using require with Typescript and Expo

查看:34
本文介绍了接到“无效电话"将要求与 Typescript 和 Expo 一起使用时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在使用 expo-cli 创建的 react-native 应用中播放一些音频.

I am trying to play some audio in a react-native app created with the expo-cli.

代码是用 typescript 编写的,有问题的代码如下所示,取自 expo.io 文档:

The code is written in typescript and the offending code looks like this, taken from the expo.io documentation:

import * as React from 'react'
import { WorkoutComponent } from "./WorkoutExecutor";
import { Audio } from 'expo';

export default class AudioPlayer {

    private async playAudio(fileName: string) {
        console.log("Playing Audio: " + fileName);
        const soundFile = './assets/sounds/' + fileName + '.mp3';
        try {
            const { sound: soundObject, status } = await Audio.Sound.createAsync(
              require(soundFile),
              { shouldPlay: true }
            );
            // Your sound is playing!
          } catch (error) {
              console.log(error);
            // An error occurred!
          }

    }
[...]
}

当应用加载时,它会给出以下错误,甚至在它带着声音进入屏幕之前

When the app loads, it gives the following error, even before it gets to the screen with the sound

[...]srcAudioPlayer.ts:Invalid call at line 13: require(soundFile)

我意识到 coe 示例是使用 javascript 而不是 typescript,但我缺少什么?

I realize that the coe example is with javascript and not typescript, but what am I missing?

我的 tsconfig.json 是 expo typescript 示例中的一个,看起来像这样

My tsconfig.json is the one from the expo typescript example and looks like this

{
  "compilerOptions": {
    "baseUrl": "./src",
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "importHelpers": true,
    "jsx": "react-native",
    "module": "es2015",
    "moduleResolution": "node",
    "noEmitHelpers": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    // Using the type definitions in @types/expo becuase they are still better than the ones provided by expo. See SvgScreen.tsx and SystemFontsScreen.tsx.
    "paths": {
      "expo": [
        "../node_modules/@types/expo",
        "../node_modules/expo"
      ],
    },
    "skipLibCheck": true,
    "strict": true,
    "target": "es2017"
  },
  "exclude": [
    "node_modules"
  ]
}

推荐答案

我通过 Twitter 获得了帮助,问题是 require() 不适用于动态值.这也解释了为什么在应用加载之前就发生了错误,因为它试图在构建或加载时解决 require,而不是像我想象的那样在运行时解决.

I got help via Twitter, and the problem is that require() does not work with dynamic values. This also explains why the errors happened before the app was even loaded, as it tried to resolve the require at build or load time and not at runtime as I had thought.

这篇关于接到“无效电话"将要求与 Typescript 和 Expo 一起使用时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆