Basics
Challenges
Classes
Debugging
Events
External Files
Flow Control
Forms
Functions
Html Elements
Installation
Interfaces
Keywords
Modules
Namespaces
Operators
Reference Files
String
Types
http://www.typescriptlang.org/docs/handbook/modules.html
Any declaration (such as a variable, function, class, type alias, or interface) can be exported by
adding the export
keyword. Exporting it will make it publicly accessible.
If you look at the image below, you can see that we export
our Logger class so that it can be used
in the export-example1
ts file. See how the export-example1
file already knew what"Logger" type was?
If I remove the export
keyword from the logger class, look what happens:
The export-example1 ts file has no knowledge of what Logger is.
We know this is working once export
is put back because of this:
My export-example.ts
file does have knowledge of the
logger.ts
file and functionality.
Now in a lot of online examples and tutorials, you will be told to use import
statements in your consuming classes.
Something like import { Logger } from "./logger";
.
I was never able to get this to work because I lacked (information and experience) on using a module loader in my project. I believe the concept is that I would have a series of separate js files in my app, each file as a module. And instead of embedding all of these js files into any given page, the loader would help one js file call another.
I was able to overcome this by compiling all the related files into a single js file and just referencing that file in my page. I defined this in my tsconfig.json file.
Important things to remember:
You need to use 'child' ts project files. One tsconfig.base.json
in the root and then one per folder.
The one in the working folder (child project file) determines the output file.
We are not using a module loader so you need to set your tsconfig.json
file to use the "system" module generation.
"module": "system",
Only by using namespaces (which define this "module") in our code can we do this without some magic module loader.
If I don't encapsulate within a common namespace and use import
instead, tsc
will compile it fine but the browser will not know what to do.