gpt4 book ai didi

javascript - typescript 默认导出

转载 作者:行者123 更新时间:2023-11-30 11:46:40 31 4
gpt4 key购买 nike

我刚开始看 Typescript,玩的时候遇到了问题。
我想编写一个库来管理一般的树结构,并只是做一些非常基本的测试来了解 TS 是如何工作的。

开始使用 3 个文件进行简单设置:

  • GForest.ts
  • GTree.ts
  • GNode.ts

目前,GForest.ts:

import * as Immutable   from "immutable"; 
import GTree from "./GTree";

export default class Forest{
public static createTree(){
let tree = new GTree();
}
}

GTree.ts:

export default class GTree{ 
constructor(){
console.log("Tree constructed");
}

public static createNode(){

}
}

我创建了一个简单的 test.js 文件来调用库(将 TS 编译为 ES5):

var GForest = require("./build/GForest"); 

console.log(GForest);

运行时

> node test

输出是:

我不明白为什么结果是:

{ default: { [Function: Forest] createTree: [Function] } }

为什么有一个以 default 为键的对象,我该如何更改它以实现所需的行为?

因此,我不能只调用:

GForest.createTree(); 

(我想通过静态工厂暴露树的创建)有什么帮助吗?

最佳答案

使用 ES6 默认导出

我引用文章ES6 In Depth: Modules来自 Mozilla:

If you’d like your own ES6 module to have a default export, that’s easy to do. There’s nothing magic about a default export; it’s just like any other export, except it’s named "default".

在您的 test.js 文件中,“默认”功能并不优雅,因为您想要使用从 ES5 语法导出的 ES6 default。我建议在 TypeScript 的帮助下使用 ES6 语法:

// test.ts
import GForest from "./build/GForest";
console.log(GForest); // { [Function: Forest] createTree: [Function] }

此代码编译为:

var GForest_1 = require("./build/GForest"); 
console.log(GForest_1.default);

直接导出类

在 TypeScript 中,您可以使用非标准语法 export = 直接导出成员。

例子:

// GForest.ts
import * as Immutable from "immutable";
import GTree from "./GTree";

class Forest{
public static createTree(){
let tree = new GTree();
}
}
export = Forest;

然后,将其与代码 ES3/5 一起使用:

// test.js
let GForest = require("./build/GForest");
console.log(GForest); // { [Function: Forest] createTree: [Function] }

... 或者,在 TypeScript 中:

// test.ts
import GForest = require("./build/GForest");
console.log(GForest); // { [Function: Forest] createTree: [Function] }

参见 the documentation on export = here .

关于javascript - typescript 默认导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40761913/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com