typescript 打字稿:如何导出变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42540745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:36:14  来源:igfitidea点击:

Typescript: How to export a variable

typescriptimportmoduleexport

提问by CrazySynthax

I want to open 'file1.ts' and write:

我想打开'file1.ts'并写:

export var arr = [1,2,3];

and open another file, let's say 'file2.ts' and access directly to 'arr' in file1.ts:

并打开另一个文件,假设'file2.ts'并直接访问file1.ts中的'arr':

I do it by:

我这样做:

import {arr} from './file1';

However, when I want to access 'arr', I can't just write 'arr', but I have to write 'arr.arr'. The first one is for the module name. How do I access directly an exported variable name?

但是,当我想访问'arr'时,我不能只写'arr',而是必须写'arr.arr'。第一个是模块名称。如何直接访问导出的变量名称?

回答by Kieran

There are two different types of export, namedand default.

有两种不同类型的导出,nameddefault

You can have multiple named exports per module but only one default export.

每个模块可以有多个命名导出,但只能有一个默认导出。

For a named export you can try something like:

对于命名导出,您可以尝试以下操作:

// ./file1.ts
const arr = [1,2,3];
export { arr };

Then to import you could use the original statement:

然后导入您可以使用原始语句:

// ./file2
import { arr } from "./file1";
console.log(arr.length);

This will get around the need for arr.arryou mentioned.

这将解决arr.arr您提到的需求。

回答by Mikael Gidmark

If you do:

如果你这样做:

var arr = [1,2,3];
export default arr;

...

...

import arr from './file1';

Then it should work

那么它应该工作