Recently I've been studying ES6, and that lead to me using Babel a lot. Being the curious type, I started looking at the Babel Github repository to know how they built this awesome tool, and know if I can somehow contribute.
However, I came across this file, and it has things like declare class BabelNodeSourceLocation {}
written all over it, and the file ends with .js.
This got me very confused, and I am now wondering whether there's a declare keyword in JavaScript that I didn't know of, or is this just a Babel-specific syntax? All my Google searches resulted in nothing.
Update: Putting the code in the Babel REPL resulted in nothing. Babel just ignored the code and did not produce any equivalent ES5 output. It also did not throw any error.
A variable can be initialized at any time before its use. The ES6 syntax used the keyword var to declare a variable. In ES5, we declare the variable like this: var x //Declaration of a variable by using the var keyword.
The declare keyword in TypeScript is used for the Ambient declaration of variables or for methods. Ambient Declarations is like an import keyword.
Local variable: When we declare a variable inside of a function. But, ECMAScript 2015 (ES6) introduced two new keywords let and const and these two keywords provide Block Scope in JavaScript.
Now, with ES6, there are three ways of defining your variables: var , let , and const .
and the file ends with .js.
That doesn't mean a lot these days :-)
I am wondering whether there's a
declare
keyword in JavaScript that I didn't know of
No, there is not.
Or is this just a Babel-specific syntax?
No. It is a type declaration file for the Flow typechecker.
With Flow, you can declare a global class that allows you to reference the class type anywhere in your project. This has no affect on runtime code and won't affect babel output.
An example from the docs:
declare class URL {
constructor(urlStr: string): URL;
toString(): string;
static compare(url1: URL, url2: URL): boolean;
};
And then in your project you can reference URL as a class type.
Similarly, you can declare other global Types, Modules, Functions, Variables. A good way to keep them organized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With