-
Notifications
You must be signed in to change notification settings - Fork 1
07 Modules
Note: When you are using export = to export your module, the import has to use require("file path of module-name") to import it. Creating Class using the export module and name this file as like a test.ts**
class ClassName{
Name: string;
constructor(name: string) {
this.Name = name;
}
FunctionName() {
return this.Name;
} }
export = ClassName;
Creating another file test1.ts in which you import module from previous file test.ts like as and in require function you will pass the file name like as
import ClassName = require("./test");
let a = new className("Ram Kapoor");
document.write(a.FunctionName())
Modules cannot work on its own, so you need module loader to locate the import dependencies as you have seen in examples shown above. The module loader available is CommonJS for nodejs and Require.js to run in the browser.
tsc --module commonjs test1.ts
tsc --module amd test1.ts
The dependent files will get converted to js file with the above command. Ii will create test.js and test1.js files
To test it using require.js, you need to create a file called main.js, which has reference to the dependencies. The folder structure of Module Files are
12-Modules/
employee.js
employeedata.js
main.js
require.js // **you can get this file from github or npm install requirejs**
TestEmployeeData.html
Now when you run this npm install requirejs command it will create one folder name as node modules inside your folder and inside this folder require folder there is one file require.js which you have to add in your folder.
Now create main.js and following code
define(function (require) {
var test = require("./test"); # here you will pass file name
var test1 = require("./test1"); # here you will pass file name
});
Next is to create an HTML file name as a test.html where you want to the output to show in Browser
<!DOCTYPE html><br>
<html><br>
<head><br>
<title>Typescript Module Example</title> <br>
<script data-main="main" src="require.js"></script> <br>
</head><br>
<body><br>
</body><br>
</html>