在 TypeScript 中创建一个全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38906359/
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
Create a global variable in TypeScript
提问by Vaccano
In JavaScript I can just do this:
在 JavaScript 中,我可以这样做:
something = 'testing';
And then in another file:
然后在另一个文件中:
if (something === 'testing')
and it will have something
be defined (as long as they were called in the correct order).
并且它将something
被定义(只要它们以正确的顺序被调用)。
I can't seem to figure out how to do that in TypeScript.
我似乎无法弄清楚如何在 TypeScript 中做到这一点。
This is what I have tried.
这是我尝试过的。
In a .d.ts file:
在 .d.ts 文件中:
interface Window { something: string; }
Then in my main.ts file:
然后在我的 main.ts 文件中:
window.something = 'testing';
then in another file:
然后在另一个文件中:
if (window.something === 'testing')
And this works. But I want to be able to lose the window.
part of it and just have my something
be global. Is there a way to do that in TypeScript?
这有效。但我希望能够失去window.
它的一部分,只拥有自己的something
全球性。有没有办法在 TypeScript 中做到这一点?
(In case someone is interested, I am really trying to setup my logging for my application. I want to be able to call log.Debug
from any file without having to import and create objects.)
(如果有人感兴趣,我真的想为我的应用程序设置我的日志记录。我希望能够log.Debug
从任何文件调用而无需导入和创建对象。)
采纳答案by tforgione
Okay, so this is probably even uglier that what you did, but anyway...
好的,所以这可能比你所做的更丑陋,但无论如何......
but I do the same so...
但我也这样做...
What you can do to do it in pure TypeScript, is to use the eval
function like so :
您可以在纯 TypeScript 中执行的操作是使用如下eval
函数:
declare var something: string;
eval("something = 'testing';")
And later you'll be able to do
以后你就可以做
if (something === 'testing')
This is nothing more than a hack to force executing the instruction without TypeScript refusing to compile, and we declare var
for TypeScript to compile the rest of the code.
这只不过是在 TypeScript 拒绝编译的情况下强制执行指令的一种技巧,我们declare var
让 TypeScript 编译其余的代码。
回答by Benoit B.
Inside a .d.ts
definition file
在.d.ts
定义文件中
type MyGlobalFunctionType = (name: string) => void
If you work in the browser, you add members to the browser's window context:
如果您在浏览器中工作,则将成员添加到浏览器的窗口上下文中:
interface Window {
myGlobalFunction: MyGlobalFunctionType
}
Same idea for NodeJS:
NodeJS 的相同想法:
declare module NodeJS {
interface Global {
myGlobalFunction: MyGlobalFunctionType
}
}
Now you declare the root variable (that will actually live on window or global)
现在您声明根变量(实际上将存在于窗口或全局上)
declare const myGlobalFunction: MyGlobalFunctionType;
Then in a regular .ts
file, but imported as side-effect, you actually implement it:
然后在一个普通.ts
文件中,但作为副作用导入,你实际上实现了它:
global/* or window */.myGlobalFunction = function (name: string) {
console.log("Hey !", name);
};
And finally use it elsewhere in the codebase, with either:
最后在代码库的其他地方使用它,或者:
global/* or window */.myGlobalFunction("Kevin");
myGlobalFunction("Kevin");
回答by edvard chen
globalThisis the future.
全球这是未来。
First, TypeScript files have two kinds of scopes
一、TypeScript文件有两种 scopes
global scope
全球范围
If your file hasn't any import
or export
line, this file would be executed in global scopethat all declaration in it are visible outside this file.
如果您的文件没有 anyimport
或export
line,则此文件将在全局范围内执行,其中的所有声明都在此文件之外可见。
So we would create global variables like this:
所以我们会像这样创建全局变量:
// xx.d.ts
declare var age: number
// or
// xx.ts
// with or without declare keyword
var age: number
// other.ts
globalThis.age = 18 // no error
All magic come from
var
. Replacevar
withlet
orconst
won't work.
所有的魔法都来自
var
。替换var
为let
或const
不起作用。
module scope
模块范围
If your file has any import
or export
line, this file would be executed within its own scope that we need to extend global by declaration-merging.
如果你的文件有 anyimport
或export
line,这个文件将在它自己的范围内执行,我们需要通过声明合并来扩展全局。
// xx[.d].ts
declare global {
var age: number;
}
// other.ts
globalThis.age = 18 // no error
You can see more about module in official docs
您可以在官方文档中查看有关模块的更多信息
回答by Vaccano
I found a way that works if I use JavaScript combined with TypeScript.
如果我将 JavaScript 与 TypeScript 结合使用,我找到了一种有效的方法。
logging.d.ts:
日志记录.d.ts:
declare var log: log4javascript.Logger;
log-declaration.js:
日志声明。js:
log = null;
initalize-app.ts
初始化-app.ts
import './log-declaration.js';
// Call stuff to actually setup log.
// Similar to this:
log = functionToSetupLog();
This puts it in the global scope and TypeScript knows about it. So I can use it in all my files.
这将其置于全局范围内,并且 TypeScript 知道它。所以我可以在我的所有文件中使用它。
NOTE: I think this only works because I have the allowJs
TypeScript option set to true.
注意:我认为这只有效,因为我将allowJs
TypeScript 选项设置为 true。
If someone posts an pure TypeScript solution, I will accept that.
如果有人发布纯 TypeScript 解决方案,我会接受。
回答by Vikash Kumar Choudhary
This is how I have fixed it:
这是我修复它的方式:
Steps:
脚步:
- Declared a global namespace, for e.g. custom.d.ts as below :
- 声明一个全局命名空间,例如 custom.d.ts 如下:
declare global {
namespace NodeJS {
interface Global {
Config: {}
}
}
}
export default global;
- Map the above created a file into "tsconfig.json" as below:
- 将上面创建的文件映射到“tsconfig.json”中,如下所示:
"typeRoots": ["src/types/custom.d.ts" ]
- Get the above created global variable in any of the files as below:
- 在任何文件中获取上面创建的全局变量,如下所示:
console.log(global.config)
Note:
笔记:
typescript version: "3.0.1".
In my case, the requirement was to set the global variable before boots up the application and the variable should access throughout the dependent objects so that we can get the required config properties.
打字稿版本:“3.0.1”。
在我的情况下,要求是在启动应用程序之前设置全局变量,并且该变量应该在整个依赖对象中访问,以便我们可以获得所需的配置属性。
Hope this helps!
希望这可以帮助!
Thank you
谢谢
回答by Dima V
im using only this
我只用这个
import {globalVar} from "./globals";
declare let window:any;
window.globalVar = globalVar;
回答by Alexey
I spent couple hours to figure out proper way to do it. In my case I'm trying to define global "log" variable so the steps were:
我花了几个小时来找出正确的方法来做到这一点。就我而言,我试图定义全局“日志”变量,因此步骤是:
1) configure your tsconfig.json
to include your defined types (src/types
folder, node_modules - is up to you):
1)配置您tsconfig.json
以包含您定义的类型(src/types
文件夹,node_modules - 由您决定):
...other stuff...
"paths": {
"*": ["node_modules/*", "src/types/*"]
}
2) create file src/types/global.d.ts
with following content (no imports!- this is important), feel free to change any
to match your needs + use window
interface instead of NodeJS
if you are working with browser:
2)创建src/types/global.d.ts
具有以下内容的文件(没有导入!- 这很重要),随意更改any
以满足您的需求+使用window
界面而不是NodeJS
如果您使用浏览器:
/**
* IMPORTANT - do not use imports in this file!
* It will break global definition.
*/
declare namespace NodeJS {
export interface Global {
log: any;
}
}
declare var log: any;
3) now you can finally use/implement log
where its needed:
3)现在你终于可以log
在需要的地方使用/实现了:
// in one file
global.log = someCoolLogger();
// in another file
log.info('hello world');
// or if its a variable
global.log = 'INFO'
回答by TrueWill
I needed to make lodash global to use an existing .js file that I could not change, only require.
我需要使 lodash 全局化以使用我无法更改的现有 .js 文件,只需要。
I found that this worked:
我发现这有效:
import * as lodash from 'lodash';
(global as any)._ = lodash;
回答by Jonathan Cardoz
As an addon to Dima V's answer this is what I did to make this work for me.
作为 Dima V 答案的补充,这就是我为使这项工作适合我所做的工作。
// First declare the window global outside the class
// First declare the window global outside the class
declare let window: any;
declare let window: any;
// Inside the required class method
// Inside the required class method
let globVarName = window.globVarName;
let globVarName = window.globVarName;