获得“无效呼叫"与Typescript和Expo一起使用require时 [英] Getting "Invalid call" when using require with Typescript and Expo

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

问题描述

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

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

该代码是用打字稿编写的,令人讨厌的代码是这样的,取自 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

[...]\src\AudioPlayer.ts:Invalid call at line 13: require(soundFile)

我意识到coe示例是使用javascript而不是打字稿的,但是我想念的是什么?

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

我的tsconfig.json是来自expo打字稿示例的一个,看起来像这样

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一起使用require时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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