[Typescript] Handle CommonJS import in Typescript

Let's say we need to use a library with commonJS code.

class Melon {
  cutIntoSlices() {
  }
}

module.exports = Melon

Then we want to import this inside our Typescript project:

import * as melonNamespace from "./melon" // typescript doesn't happen about this
// This moudle can only be referneced with ECMAScrip
// import/exports by turing on the'esModuleInterop' flag and referencing its default export.

So how to avoid this.

Solution 1, change library how it's export thing

class Melon {
  cutIntoSlices() {
  }
}

module.exports = { Melon } // <-- change to named export

If we change to named export, then it should work.

import {Melon} from "./melon"

But if the code is inside a library, you cannot do this change of course.

Solution 2:

Change the tsconfig setting as it suggested: esModuleInterop: true, but suggest not to do so.
If you are writing a lib, don't turn on this setting, because it forces your consumers also turns on this settings as well.

class Melon {
  cutIntoSlices() {
  }
}

module.exports = Melon

index.ts

import Melon = require('./melon')
posted @ 2024-01-28 20:36  Zhentiw  阅读(5)  评论(0编辑  收藏  举报