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.
Solution 3 (recommended)
class Melon {
cutIntoSlices() {
}
}
module.exports = Melon
index.ts
import Melon = require('./melon')
标签:CommonJS,Typescript,exports,library,export,Melon,import
From: https://www.cnblogs.com/Answer1215/p/17993296