安装:
npm install -g typescript
运行:
tsc helloworld.ts ----------生成相应的helloworld.js文件
gulp构建ts项目:
1、mkdir gulpTsApp
2、cd gulpTsApp
3、mkdir src
4、mkdir dist
5、npm init
6、npm install -g gulp-cli
7、npm install --save-dev typescript gulp gulp-typescript
HELLOWORLD:
1.src下面新建helloworld.ts文件:
function hello(compiler:string){
console.log(`Hellofrom${compiler}`);
}
hello("TypeScript");
2、在工程的根目录proj下新建一个tsconfig.json文件:
{
"files": [
"src/helloworld.ts"
],
"compilerOptions": {
"noImplicitAny": true,
"target": "es5"
}
}
3、在工程根目录下,新建一个gulpfile.js文件:
vargulp=require("gulp");
var ts=require("gulp-typescript");
var tsProject=ts.createProject("tsconfig.json");
gulp.task("default",function(){
returnts Project.src()
.pipe( tsProject())
.js.pipe(gulp.dest("dist"));
});
4、运行helloworld:
gulp
node dist/main.js
Browserify:
1、npm install --save-dev browserify tsify vinyl-source-stream
2、新建index.html页面:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Hello World!</title>
</head>
<body>
<p id="greeting">Loading ...</p>
<script src="bundle.js"></script>
</body>
</html>
3、新建main.ts文件:
import{sayHello}from"./greet";
function showHello(divName:string,name:string){
const elt=document.getElementById(divName);
elt.innerText=sayHello(name);
}
showHello("greeting","TypeScript");
4、新建gulpfile.js文件:
var gulp=require("gulp");
var browserify=require("browserify");
var source=require('vinyl-source-stream');
var tsify=require("tsify");
var paths={
pages:['src/*.html']
};
gulp.task("copy-html",function(){
return gulp.src(paths.pages)
.pipe(gulp.dest("dist"));
});
gulp.task("default",["copy-html"],function(){
return browserify({
basedir:'.',
debug:true,
entries:['src/main.ts'],
cache:{},
packageCache:{}
})
.plugin(tsify)
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest("dist"));
});
5、运行:gulp ,之后打开index.html页面即可
Watchify、Bable、Uglify运用:
1、安装watchify:
npm install --save-dev watchify gulp-util
2、安装uglify及其他相关插件:
npm install --save-dev gulp-uglify vinyl-buffer gulp-sourcemaps
3、安装Babel以及其他相关插件:
npm install --save-dev babelify babel-preset-es2015 vinyl-buffer gulp-sourcemaps
4、修改gulpfile.js文件:
var gulp=require('gulp');
var browserify=require('browserify');
var source=require('vinyl-source-stream');
var tsify=require('tsify');
var sourcemaps=require('gulp-sourcemaps');
var buffer=require('vinyl-buffer');
var paths={pages:['src/*.html']};
gulp.task('copyHtml',function(){
return gulp.src(paths.pages).pipe(gulp.dest('dist'));
});
gulp.task('default',['copyHtml'],function(){
return browserify({
basedir:'.',
debug:true,
entries:['src/main.ts'],
cache:{},
packageCache:{}
})
.plugin(tsify)
.transform('babelify',{presets:['es2015'],extensions:['.ts']})
.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps:true}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('dist'));
});
5、修改tsconfig.js:
{
"files": [ "src/main.ts" ],
"compilerOptions": {
"noImplicitAny": true,
"target": "es2015" }
}
将react、webpack、typescript结合使用:
1、mkdir reactTypescriptApp --> cd reactTypescriptApp --> mkdir src --> cd src --> mkdir components --> npm init
2、npm install -g webpack
3、npm install --save react react-dom @types/react @types/react-dom
4、npm install --save-dev typescript awesome-typescript-loadersource-map-loader
5、创建tsconfig.json文件:
{
"compilerOptions":{
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"jsx": "react"
},
"include": [ "./src/**/*" ]
}
6、创建hello.tsx文件:
import * as React from"react";
export interface HelloProps{
compiler:string;
framework:string;
}
export const Hello=(props:HelloProps)=><h1>Hellofrom{props.compiler}and{props.framework}!</h1>;
7、创建index.tsx:
import * as React from "react";
import * as ReactDOM from "react-dom";
import{ Hello }from"./components/Hello";
ReactDOM.render(
<Hello compiler="TypeScript" framework="React"/>,
document.getElementById("example"));
8、创建index.html:
<!DOCTYPE html>
<html>
<head>
<metacharset="UTF-8"/>
<title>Hello React!</title>
</head>
<body>
<div id="example"></div>
<!-- Dependencies -->
<script src="./node_modules/react/umd/react.development.js"></script>
<script src="./node_modules/react-dom/umd/react-dom.development.js"></script>
<!-- Main --><script src="./dist/bundle.js"></script>
</body>
</html>
9、创建webpack.config.js
10、执行 webpack
知识点正文:
一、基础类型:
布尔、数字、字符串、数组、元祖、枚举、任意值、空值、null和undefined、never、类型断言
let isDone:boolean=false;
let decLiteral:number=6;
let name:string="bob";
let name:string=`Gene`;
let age:number=37;
let sentence:string=`Hello,my name is${name}
let list:number[]=[1,2,3];
元组类型允许表示一个已知元素数量和类型的数组:
let x:[string,number];
x=['hello',10];//ok
x=[10,'hello'];// Error
enum Color{Red,Green,Blue}
let c:Color=Color.Green;
enum Color{Red=1,Green,Blue}
let colorName:string=Color[2];
let notSure:any=4;
notSure="maybe a string instead";
notSure=false;// okay, definitely a boolean
let list:any[]=[1,true,"free"];
function warnUser():void{
alert("This is my warning message");
}
let u:undefined=undefined;
let n:null=null;
二、变量声明
var a=10;
for(vari=0;i<10;i++){
setTimeout(function(){ console.log(i); },100*i);
}
for(var i=0;i<10;i++){
// capture the current state of 'i'// by invoking a function with its current value
(function(i){
setTimeout( function(){ console.log(i); },100*i );
})(i);
}
function sumMatrix(matrix:number[][]){
let sum=0;
for(leti=0;i<matrix.length;i++){
var currentRow=matrix[i];
for(leti=0;i<currentRow.length;i++){
sum+=currentRow[i];
}
}
return sum;
}
for(let i=0;i<10;i++){
setTimeout(function(){
console.log(i);
},100*i);
}
数组结构:
let input=[1,2];
let[first,second]=input;
[first,second]=[second,first];
function f([first,second]:[number,number]){
console.log(first);console.log(second);
}
let [first,...rest]=[1,2,3,4];
let [first]=[1,2,3,4];
let [,second,,fourth]=[1,2,3,4];
let o={a:"foo",b:12,c:"bar"};let {a,b} =o;
({a,b}={a:"baz",b:101});
let {a,...passthrough}=o;
let total=passthrough.b+passthrough.c.length;
let {a:newName1,b:newName2}=o;
let {a,b}:{a:string,b:number}=o;
let {a: otherName1,b:otherName2}: {a:string,b: number} = o
function keepWholeObject(wholeObject:{a:string,b?:number}){
let {a,b=1001}=wholeObject;
}
type C={a:string,b?:number}
function f({a,b=1}:C):void{// ...}
function f({a,b}={a:"",b:0}):void{// ...}
let first=[1,2];let second=[3,4];let bothPlus=[0,...first,...second,5];
let defaults={food:"spicy",price:"$$",ambiance:"noisy"};
let search={...defaults,food:"rich"};
class C{
p=12;
m(){}
}
let c=newC();
let clone={...c};
clone.p;// ok
clone.m();// error!
三、接口
interface SquareConfig{
color?:string;
width?:number;
}
function createSquare(config:SquareConfig):{color:string;area:number}{
let newSquare={color:"white",area:100};
if(config.color){
// Error: Property 'clor' does not exist on type 'SquareConfig'
newSquare.color=config.clor;}
if(config.width){
newSquare.area=config.width*config.width;
}
return newSquare;
}
let mySquare=createSquare({color:"black"});
interface Point{
readonly x:number;
readonly y:number;
}
let p1:Point={x:10,y:20};
p1.x=5;// error!
let a:number[]=[1,2,3,4];
let ro:ReadonlyArray<number>=a;
ro[0]=12;// error!
ro.push(5);// error!
ro.length=100;// error!
a=ro;// error!
interface SquareConfig{
color?:string;
width?:number;
[propName:string]:any;
}
interface SearchFunc{
(source:string,subString:string):boolean;
}
let mySearch:SearchFunc;
mySearch=function(source:string,subString:string){
let result=source.search(subString);return result>-1;
}