将 require 与 Typescript 和 Expo 一起使用时出现“无效调用”

2024-01-06

我正在尝试在使用 expo-cli 创建的反应本机应用程序中播放一些音频。

该代码是用打字稿编写的,有问题的代码如下所示,取自expo.io 文档 https://docs.expo.io/versions/latest/sdk/audio/:

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!
          }

    }
[...]
}

当应用程序加载时,即使在声音到达屏幕之前,也会出现以下错误

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

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

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

{
  "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在构建或加载时而不是像我想象的那样在运行时。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 require 与 Typescript 和 Expo 一起使用时出现“无效调用” 的相关文章

随机推荐