PL
TypeScript - skompiluj wszystkie pliki TS do jednego JS
3 points
W języku TypeScript można skompilować wszystkie pliki *.ts
do jednego pliku *.js
w następujący sposób.
Pobierz cały kod źródłowy z jednego miejsca tutaj.
tsconfig.json
plik:
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
}
Uwaga:
"outFile" : "./out.js"
definiuje pojedynczy plik wyjściowy kodu źródłowego.
Person.ts
plik:
xxxxxxxxxx
1
export class Person
2
{
3
public constructor(public name : string, public age : number)
4
{
5
// nothing here ...
6
}
7
8
public toString() : string
9
{
10
return `{ Name: ${this->name}, Age: ${this->age} }`;
11
}
12
}
Printer.ts
plik:
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
plik:
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
plik:
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>
Uwaga: powyższy kod źródłowy używa https://requirejs.org/ modułu ładującego.
Kompilacja i uruchomienie:
- Otwórz konsolę (np. Bash)
- Przejdź do katalogu projektu
- Wybierz
tsc
program do kompilacji wszystkich plików do jednego - Otwórz plik index.htm w przeglądarce internetowej
Podgląd konsoli Bash:
xxxxxxxxxx
1
$ cd /C/Project
2
$ tsc
/C/Project
podgląd katalogu:
Uwagi:
- po uruchomieniu polecenia
tsc
powinny pojawić się trzy nowe pliki (out.*
).out.d.ts
zawiera wszystkie deklaracje (przydatne w przypadku intelisense i integracji plikuout.js
z innymi projektami TypeScript)out.js.map
zawiera mapowanie rozwojowe dla procesu debugowaniaout.js
zawiera cały kod źródłowy transponowany do pojedynczego pliku javascript
Podgląd w przeglądarce internetowej: