When you use reference comments, you have to load all of the modules yourself (i.e. add multiple script tags, or combine and minify the files etc).
If you want to use a module loader, you need to use import
statements, which will be converted into require method calls for the module loader of your choice (probably RequireJS for the web).
Example 1 - DIY
<script src="/src/Company.js"></script>
<script src="/src/User.js"></script>
<script src="app.js"></script>
Example 2 - RequireJS
src/Company.ts
export class Job {
public title: string;
public description: string;
constructor(title: string, desc: string) {
this.title = title;
this.description = desc;
}
}
Note that I have removed the module
declaration. The file name becomes the module name when you are importing the modules using RequireJS...
src/User.ts
import company = module('Company');
export class Account {
public userName: string;
private _password: string;
constructor(user: Person) {
this.userName = user.first[0] + user.last;
this._password = '12345';
}
}
export class Person {
public first: string;
public last: string;
private myJob: company.Job;
private myAccount: Account;
constructor(firstName: string, lastName: string) {
this.first = firstName;
this.last = lastName;
}
public getName(): string {
return this.first + ' ' + this.last;
}
public setJob(job: company.Job) {
this.myJob = job;
}
public setAccount(acct: Account) {
this.myAccount = acct;
}
public toString(): string {
return "User: " + this.getName()
+ "\nUsername: " //+ this.myAccount.userName
+ "\nJob: " + this.myJob.title;
}
}
A couple of changes here - we have the import
statement rather than a comment that points to the file. We also reference Account
in here rather than User.Account
. Again, the enclosing module is gone as the file is the module.
app.ts
import Company = module('src/Company');
import User = module('src/User');
(function go() {
var user1: User.Person = new User.Person('Bill', 'Braxton');
var acct1: User.Account = new User.Account(user1);
var job1: Company.Job = new Company.Job('Greeter', 'Greet');
user1.setAccount(acct1);
user1.setJob(job1);
console.log(user1.toString());
} ());
Import statements again here. As a side note, the go
function looks to be immediately executing, so you shouldn't need to call it a second time manually - you could remove the function name to stop this being done by accident.
Index.html
<script data-main="app.js" src="require.js"></script>
You need to include the RequireJS script in your project. You only need to point it at your first file and it will load all the rest. You'll notice in your compiled JavaScript that your import
statements get converted into calls to the RequireJS require
function:
var Company = require("./src/Company");
var User = require("./src/User");
This triggers RequireJS to load the script for you.
You can also use RequireJS manually if you want more control (i.e. use the require
method directly rather than using import
statements.