Modules in TypeScript
Modules is another feature of TypeScript. TypeScript allows encapsulation of implementation in classes at design time with the ability to restrict use of private members, but cannot allow encapsulation at runtime because all object properties are accessible at runtime. In JavaScript, the only way to allow encapsulation at runtime is to use the module pattern, and if you want to allow encapsulation of implementation in classes at runtime time with the use of private members, then you can also use modules in TypeScript. TypeScript also supports external modules, which are files that contain top-level export and import directives.
Syntax
module moduleName {//............body} |
Step 1
Open Visual Studio 2012 and click on "File" menu -> "New" -> "Project". A window will be opened. Provide the name of your application like "ExampleOfModules", then click on the Ok button.
Step 2
After Step 1 your project has been created. Solution Explorer, which is at the right side of Visual Studio, contains the js file, ts file, css file and html files.
Step 3
The code of the Modules program follows.
ExampleOfModules.ts
module Mcn {
var message = "Welcome in Mcn Solution !";
exportfunction CompName()
{
document.write(message);
}
}
Mcn.CompName(); |
Note In the above declared program, the variable "message" is a private feature of the module, but the function "CompName" is exported from the module and accessible to code outside of the module.
default.html
<!DOCTYPEhtml>
<htmllang="en"xmlns="http://www.w3.org/1999/xhtml">
<head>
<metacharset="utf-8"/>
<title>TypeScript Modules</title>
<linkrel="stylesheet"href="app.css"type="text/css"/>
<scriptsrc="app.js"></script>
</head>
<body>
<divid="content"/>
</body> </html> |
app.js
var Mcn;
(function (Mcn) {
var message = "Welcome in Mcn Solution !";
function CompName() {
document.write(message);
}
Mcn.CompName = CompName;
})(Mcn || (Mcn = {}));
Mcn.CompName(); |
Step 4
Output