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

Kei*_*ith 7 javascript typescript ecmascript-6 typescript-typings

我有一个thing.d.ts带有全局定义的外部库文件:

declare var thing: ThingStatic;
export default thing;
Run Code Online (Sandbox Code Playgroud)

我在TypeScript中引用了npm模块:

import thing from 'thing';
...
thing.functionOnThing();
Run Code Online (Sandbox Code Playgroud)

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

const thing_1 = require("thing");
...
thing_1.default.functionOnThing();
Run Code Online (Sandbox Code Playgroud)

然后抛出一个错误:

无法读取未定义的属性'functionOnThing'

为什么TypeScript会.defaultthing_1和之间添加functionOnThing()

没有名为defaulton的属性ThingStatic,并且default.d.ts文件定义的底层JS对象上没有属性.

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

Rya*_*ugh 13

import thing from 'thing';
Run Code Online (Sandbox Code Playgroud)

这行代码意味着 " default从模块导入导出'thing'并将其绑定到本地名称thing".

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

你可能想写的是

import * as thing from 'thing';
Run Code Online (Sandbox Code Playgroud)


Kei*_*ith 6

这似乎是全球TS定义和错误"module": "commonjs"tsconfig.json

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

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

declare var thing: ThingStatic;
export thing; // Explicit export for thing
export default thing; // Default export for thing
Run Code Online (Sandbox Code Playgroud)

现在require将返回此上下文,因此对于commonjs模块:

import module from 'thing';
var thing = module.default; // From the default export
var alsoThing = module.thing; // From the named export
Run Code Online (Sandbox Code Playgroud)

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

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