在 Typescript 和 Expo 中使用 require 时出现“无效调用”

mor*_*ras 2 require typescript react-native expo

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

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

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

    }
[...]
}
Run Code Online (Sandbox Code Playgroud)

当应用程序加载时,它会给出以下错误,甚至在它到达带有声音的屏幕之前

[...]\src\AudioPlayer.ts:Invalid call at line 13: require(soundFile)
Run Code Online (Sandbox Code Playgroud)

我意识到 coe 示例是使用 javascript 而不是打字稿,但我错过了什么?

我的 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"
  ]
}
Run Code Online (Sandbox Code Playgroud)

mor*_*ras 8

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

  • 这就解释了这个错误。你有解决办法吗? (9认同)