What is best practice for imports in typescript?

1k views Asked by At

While trying to get a third party node module "mp4frag" to play nice with my typescript code, I tried several solutions as prompted by the error messages from eslint. There didn't appear to be any @types/mp4frag module that I could use. So I tried to make my own (as eslint recommended). Note that mp4frag is a .js module that contains a class definition with a constructor and several methods. The last line of the module after the class definition is: module.exports = Mp4Frag. I started with a simple declare module mp4frag statement in a declaration file. That didn't really work, so I did some more web research and finally ended up the the following mp4frag.d.ts file:

declare module 'mp4frag' {
  import { Transform } from 'stream'

  class Mp4Frag extends Transform {
    constructor(options?: {
      hlsPlaylistBase?: string
      hlsPlaylistSize?: number
      hlsPlaylistExtra?: number
      hlsPlaylistInit?: boolean
      segmentCount?: number
    })
    mime: string
    initialization: Buffer | null
    segment: Buffer | null
    timestamp: number
  }
  export = Mp4Frag
}

And my imports look like this:

import { ChildProcess, spawn } from 'child_process'
import * as fs from 'fs'
import * as Path from 'path'
import * as socketio from 'socket.io'

import systemConfig from '../../config'
import { Camera } from '../../interfaces/cameras'
import { Mp4Client } from './mp4Client'

import Mp4Frag = require('mp4frag')

At this point the code seems to work fine. My only complaint might be that the import sorter extension doesn't seem to know what to do with the import Mp4Frag statement. It appears to treat it like a non-import statement. One other note is that I tried turning on the ESmoduleinterop option in tsconfig, but then my import of express was giving me an error. Perhaps I should have gone down that route and fixed the express import error. But instead I turned the option back off. So, my question is whether the structure of my imports and the structure of my .d.ts file are best practices.

0

There are 0 answers