为什么 TypeScript 将 .default 添加到全局定义的导入中?

Why is TypeScript adding .default to a globally defined import?

我有一个外部库 thing.d.ts 文件,里面有全局定义:

declare var thing: ThingStatic;
export default thing;

我在我的 TypeScript 中引用了 npm 模块:

import thing from 'thing';
...
thing.functionOnThing();

当我转译 TS(针对 ES6)时,它看起来像这样:

const thing_1 = require("thing");
...
thing_1.default.functionOnThing();

然后会抛出一个错误:

Cannot read property 'functionOnThing' of undefined

为什么 TypeScript 在 thing_1functionOnThing() 之间添加 .default

ThingStatic 上没有名为 default 的 属性,.d.ts 的基础 JS 对象上也没有 default 属性文件定义。

为什么 TypeScript 添加 属性 以及如何停止它?

import thing from 'thing';

这行代码的意思是"import the default export from the module 'thing' and bind it to the local name thing".

TypeScript 按照您的要求执行并访问模块对象的 default 属性。

您可能想写的是

import * as thing from 'thing';

这似乎是全局 TS 定义和 tsconfig.json 中的 "module": "commonjs" 的错误。

您可以使用全局 TS 定义并将所有输出拼接成一个文件,也可以使用模块并直接导入它们。

这里的错误是由于 require return 模块上下文,而 default 的名称无关紧要 - 它总是变成 default.. .

declare var thing: ThingStatic;
export thing; // Explicit export for thing
export default thing; // Default export for thing

现在 require 将 return 这个上下文,所以 commonjs 模块:

import module from 'thing';
var thing = module.default; // From the default export
var alsoThing = module.thing; // From the named export

然而,我发现这是不一致的,所以切换到 es6 模块:

import thing from './thing'; // Import default
import { thing } from './thing'; // Import named
const thing = (await import('path/to/thing.js')).default; // Import dynamic