Workaround for Typescript esModuleInterop Error

I recently had to work with the Hubspot API, so I installed their Node library. Everything was working well testing the new code with ts-node. However, when I built the Typescript file with tsc, I got a bunch of errors coming from the Hubspot library:

This module is declared with using ‘export =’, and can only be used with a default import when using the ‘esModuleInterop’ flag.

To fix this, I found the esModuleInterop flag in my tsconfig.json file and switched to true. When I ran the build again, and I got even more errors, this time pointing to the import style of “import * as ___ from ___”. For example, import * as moment from 'moment'.

To solve these errors, I just had to switch the import statement slightly to import moment from moment; The problem was that I had over 100 Typescript files in the project using that style of import. I didn’t want to refactor a bunch of files for this one Hubspot library, mainly because of potential issues that may creep in when I released to Production. Plus, that import style I was using is perfectly valid according to the Typescript docs.

I was a bit stumped on what to do for a while, until I decided to just try and import the one Hubspot library “node style”, using require. I just switched import * as hubspot from '@hubspot/api-client' to const hubspot = require('@hubspot/api-client'). This worked well and all the original build errors disappeared. The only problem was that I lost Intellisense using the node-style import, but this was OK since the library was pretty straightforward.

So if you are faced with a similar situation, just try an import with require, and you should be good to go.

Leave a comment