When you neglect to define compiler options in the command line for tsc
and lack a tsconfig.json
file, typescript resorts to using default settings. As per the guidance provided in the typescript documentation, the defaults are set to es3
for the emitted language and commonjs
as the module loader. Dissatisfied with these options, I opt to specify different configurations within a tsconfig.json
file. Follow this setup for your project, which may initially feel like a significant effort but can be saved as a template, eliminating future repetition. This guide assumes that your machine is properly configured with npm
.
To begin, create a new project in VS 2017, selecting ASP.NET Web Application (.NET Framework) as the template. Though unconventional, this choice results in a streamlined project void of unnecessary components. In the subsequent wizard page, opt for an Empty project, unchecking all boxes including authentication. Complete the wizard process.
At the root level of your project, add the following files:
package.json:
{
"version": "1.0.0",
"name": "asp.net",
"author": "you",
"private": true,
"dependencies": {
"core-js": "^2.5.3",
"systemjs": "^0.21.0"
}
}
tsconfig.json:
{
"compilerOptions": {
"module": "system",
"target": "es5",
"noImplicitAny": true,
"noEmitOnError": true,
"sourceMap": true
},
"files": [
"app/app.ts"
],
"exclude": [
"node_modules"
]
}
system.config.js:
(function (global) {
SystemJS.config({
paths: {
'npm:': '/node_modules/'
},
map: {
app: '/app'
},
packages: {
app: {
main: 'app.js',
defaultExtension: 'js'
}
}
})
})(this);
index.html:
<!DOCTYPE html>
<html>
<head>
<base href="/" />
<meta charset="utf-8" />
<title>Typescript with SystemJS and Modules Demo</title>
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/systemjs/dist/system.js"></script>
<script src="system.config.js"></script>
<script>
SystemJS.import("app/app.js").catch(function (e) { console.log(e); });
</script>
</head>
<body>
<div id="personDiv"></div>
</body>
</html>
Additionally, create an app
folder and include the following two files within it:
app.ts:
import { Person } from "./person";
export class App {
constructor() {
let person: Person = new Person();
let div: HTMLDivElement = <HTMLDivElement>document.getElementById('personDiv');
div.innerHTML = person.getName();
}
}
// Use this assignment to start execution.
let a: App = new App();
// The following doesn't appear to work with SystemJS. It does with plain TypeScript.
// It is probably because SystemJS already defines a listener for window.onload,
// although I haven't verified that.
//window.onload = () => {
// let a: App = new App();
// let person = new Person();
// alert(person.getName);
//}
person.ts:
export class Person {
fullName: string;
constructor() {
this.fullName = "Test Guy";
}
getName():string {
return this.fullName;
}
}
After completing the setup, build and run the application to observe successful imports.