Javascript angular2(typescript) 从另一个文件导出变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37649844/
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-08-23 20:34:05  来源:igfitidea点击:

angular2(typescript) export variables from another file

javascripttypescriptangular

提问by user2924127

In Nodejs I have a page called variables.jswhich looks something like this:

在 Nodejs 中,我有一个名为的页面variables.js,它看起来像这样:

exports.var1= 'a';
exports.var2= 'b';

This file holds variables I use within in my application all in one place.

该文件将我在应用程序中使用的变量集中在一处。

Then inside of another page I call this page using:

然后在另一个页面内,我使用以下方法调用此页面:

var variables= require('./variables');

Now I have access to the variable sin that page by using it like this for example:

现在我可以通过使用它来访问该页面的变量 sin,例如:

alert(variables.var1);

I would like to do the same thing inside of angular2 (typescript). I have tried to play with exports and imports but I can't get it to work. How can I do this inside of angular2 using typescript?

我想在 angular2 (打字稿)中做同样的事情。我曾尝试使用导出和导入,但无法正常工作。如何使用打字稿在 angular2 内部执行此操作?

回答by Günter Z?chbauer

variables.ts

变量.ts

export var var1:string = 'a';
export var var2:string = 'b';

other-file.ts

其他文件.ts

import {var1, var2} from './variables';

alert(var1);

or

或者

import * as vars from './variables';

alert(vars.var1);

See also Barrelat https://angular.io/guide/glossary#barrel

另请参见Barrelhttps://angular.io/guide/glossary#barrel

回答by basarat

have tried to play with exports and imports but I can't get it to work. How can I do this inside of angular2 using typescript?

曾尝试使用导出和导入,但我无法使其正常工作。如何使用打字稿在 angular2 内部执行此操作?

Just use the exportkeyword and importkeyword. This is just ES6 and magically works with TypeScript ;)

只需使用export关键字和import关键字。这只是 ES6 并且神奇地与 TypeScript 一起工作;)

Export:

出口:

export var1 = 'a'

Import:

进口:

import {var1} from './variables';

More

更多的

TypeScript modules are covered here : https://basarat.gitbooks.io/typescript/content/docs/project/modules.html

TypeScript 模块在这里介绍:https: //basarat.gitbooks.io/typescript/content/docs/project/modules.html