Syntax error when importing MP3 files into Typescript

I’m writing a node.js + typescript script that I’d like to run in the CLI using ts-node, and which imports MP3 files like so:

import SomeSoundFile from "./some-sound-file.mp3";

I understand that I need to let typescript know about mp3 files, and I’ve created a type declaration file which looks like this:

declare module "*.mp3";

And I’ve included the type declaration file in my typescript config file. However, when I try to execute my script, I see the following error:

$ ts-node check-audio.ts
./some-sound-file.mp3:1
����


SyntaxError: Invalid or unexpected token
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1033:15)
    ...

I’ve read other SO articles which state that the only thing required to accommodate mp3 files is to add the type definition, which I’ve done. However, ts-node seems to be attempting to parse the MP3 file and I’ve no idea why. I’ve also tried use ES5-style imports (i.e. require(...)) but that does not seem to make a difference. What am I missing here?

  • What do you expect when you import a mp3 file? What is SomeSoundFile supposed to be? A stream? An object? A string? You probably need a bundler with the appropriate loader to handle mp3 imports.

    – 

  • @kelsny excellent question. In this case I simply want to ensure that the mp3 file exists. I realize I can do this other ways (i.e. fs.existsSync) but I have a ts file which is auto-generated, and which contains all the imports, and I’d like to validate that it’s accurate by simply importing the module.

    – 

  • Hmm alright. If you’re running some kind of build script to generate the TS file, could you not just add in a step to check if the mp3 file exists?

    – 

  • @kelsny I think that may be a good solution, that way I can simply say, if building of the import file succeeds, the files are there.

    – 

Leave a Comment