DE
TypeScript - alle ts-Dateien zu einem js kompilieren
3 points
In TypeScript ist es mögllich, alle *.ts
Dateien auf folgende Art und Weise zu einer *.js
Datei zu kompilieren.
Den gesamten Quellcode kann man hier herunterladen.
tsconfig.json
Datei:
xxxxxxxxxx
1
{
2
"version" : "3.0.3",
3
"compilerOptions" : {
4
"module" : "amd",
5
"removeComments" : true,
6
"outFile" : "./out.js",
7
"baseUrl" : "./",
8
"sourceMap" : true,
9
"alwaysStrict" : true,
10
"declaration" : true,
11
},
12
"include": [
13
"./**/*.ts"
14
],
15
"exclude": [
16
"./out.d.ts"
17
]
18
}
Hinweis:
"outFile" : "./out.js"
definiert die Ausgabedatei für einen einzelnen Quellcode.
Person.ts
Datei:
xxxxxxxxxx
1
export class Person
2
{
3
public constructor(public name : string, public age : number)
4
{
5
// nichts hier ...
6
}
7
8
public toString() : string
9
{
10
return `{ Name: ${this->name}, Age: ${this->age} }`;
11
}
12
}
Printer.ts
Datei:
xxxxxxxxxx
1
import { Person } from "./Person";
2
3
export class Printer
4
{
5
public static printPerson(person : Person) : void
6
{
7
console.log(person.toString());
8
}
9
10
public static printPersons(persons : Array<Person>) : void
11
{
12
for(let entry of persons)
13
this.printPerson(entry);
14
}
15
}
Main.ts
Datei:
xxxxxxxxxx
1
import { Person } from "./Person";
2
import { Printer } from "./Printer";
3
4
let persons = new Array<Person>();
5
6
persons.push(new Person('John', 30));
7
persons.push(new Person('Adam', 23));
8
persons.push(new Person('Kate', 41));
9
10
Printer.printPersons(persons);
index.htm
Datei:
xxxxxxxxxx
1
2
<html lang="en">
3
<head>
4
<meta charset="utf-8">
5
<title>Example</title>
6
<meta name="description" content="Example typescript files compilation to single javascript file.">
7
<meta name="author" content="dirask.com">
8
<!--
9
<script src="https://requirejs.org/docs/release/2.3.6/minified/require.js"></script>
10
-->
11
<script src="https://requirejs.org/docs/release/2.3.6/comments/require.js"></script>
12
<script src="out.js"></script>
13
</head>
14
<body>
15
<script>
16
17
require( [ 'Main' ] );
18
19
</script>
20
</body>
21
</html>
Hinweis: Der obige Quellcode verwendet den https://requirejs.org/ Modullader.
Zusammenstellung und Ausführung:
- Konsole öffnen (z. B. Bash)
- Zum Projektverzeichnis gehen
- Das
tsc
Program ausführen, um alle Dateien zu einer zu kompilieren - index.htm im Webbrowser öffnen
Vorschau der Bash-Konsole:
xxxxxxxxxx
1
$ cd /C/Project
2
$ tsc
/C/Project
Verzeichnisvorschau:
Hinweise:
- Nach dem Ausführen des Befehls
tsc
sollten drei neue Dateien (out.*
) angezeigt werden.out.d.ts
enthält alle Deklarationen (nützlich für die Datei Intellisense und Integrationout.js
mit anderen Typescript-Projekten)out.js.map
enthält Entwicklungszuordnungen für den Debug-Prozessout.js
enthält den gesamten Quellcode, der in eine einzelne JavaScript-Datei transpiliert wurde
Webbrowser-Vorschau:
Den gesamten Quellcode kann man hier herunterladen.