[Typescript] CommonJS Interop

From source: https://www.typescript-training.com/course/intermediate-v1/03-modules/

Things can sometimes get a bit tricky when consuming CommonJS modules that do things that are incompatible with the way ES Modules typically work.

Most of the time, you can just convert something like

const fs = require("fs")

into

// namespace import
import * as fs from "fs"

but occasionally, you’ll run into a rare situation where the CJS module you’re importing from, exports a single thing that’s incompatible with this namespace import technique.

Here’s a small example of where the namespace import fails:

While this error message is accurate, you may NOT want to follow the advice it provides in all situations.

If you need to enable the esModuleInterop and allowSyntheticDefaultImports compiler flags in order to allow your types to compile, anyone who depends on your types will also have no choice but to enable them.

Thankfully we have another option here — the use of an older module loading API that imports the code properly, and matches up the type information as well

////////////////////////////////////////////////////////
// @filename: fruits.ts
function createBanana() {
  return { name: "banana", color: "yellow", mass: 183 }
}
 
// equivalent to CJS `module.exports = createBanana`
export = createBanana
////////////////////////////////////////////////////////
// @filename: smoothie.ts
 
import createBanana = require("./fruits")
const banana = createBanana()
import createBanana = require("./fruits")

we have solved this by avoiding the use of an ECMAScript import/export. After all, the code we’re referring to here is not following the ES module spec to begin with

The compiled output of this file will still be what we’re looking for in the CJS world

 

"use strict";
function createBanana() {
    return { name: "banana", color: "yellow", mass: 183 };
}
module.exports = createBanana;
////////////////////////////////////////////////////////
 

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var createBanana = require("./fruits");
var banana = createBanana();

 

posted @   Zhentiw  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-08-10 [CSS] Create Complex Shapes with CSS Clip Path and Border Radiusc (border-radius & clip-path)
2020-08-10 [CSS] Create a Responsive Unit and Container
2020-08-10 [Javascript] Number, toLocaleString() & Intl
2020-08-10 [XState] Actor Model
2018-08-10 [Algorithms] Determine if a string is a palindrome
2018-08-10 [Algorithm] Determine if two strings are an anagram
2017-08-10 [D3] Build a Column Chart with D3 v4
点击右上角即可分享
微信分享提示