type scripte 项目创建

2018-08-21  本文已影响0人  廖全磊LesterLiao

创建项目

npm init

安装相应的库

npm install --save-dev typescript

npm install --save-dev nodemon

npm install --save-dev ts-node

npm install --save-dev @types/koa

npm install --save koa

package.json内容差不多如下

{
  "name": "learn-ts",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon -x ts-node --inspect app.ts",
    "start": "node dist/app.js",
    "build": "tsc "
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/koa": "^2.0.46",
    "nodemon": "^1.17.5",
    "ts-node": "^6.1.0",
    "typescript": "^2.9.1"
  },
  "dependencies": {
    "koa": "^2.5.1"
  }
}

生成tsconfig.json文件

tsc --init
tsconfig.json

文件设置如下

{
  "compilerOptions": {
    "outDir": "./dist/",
    "module": "commonjs",
    "noImplicitAny": true,
    "preserveConstEnums": true,
    "sourceMap": true,
    "target": "es5",
    "allowJs": true
  }
}

在根目录下创建 app.ts文件

import * as Koa from 'koa'

const app = new Koa()

app.use(ctx => {
  ctx.body = 'xiadd'
})

app.listen(8002, () => {
  console.log('server is running')
})

输入命令进行编译和运行

npm run build

npm run start
 

也可以创建run.sh文件 将运行命令写入该文件

创建项目

npm init
 

安装相应的库

npm install --save-dev typescript

npm install --save-dev nodemon

npm install --save-dev ts-node

npm install --save-dev @types/koa

npm install --save koa

package.json内容差不多如下

{
  "name": "learn-ts",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon -x ts-node --inspect app.ts",
    "start": "node dist/app.js",
    "build": "tsc "
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/koa": "^2.0.46",
    "nodemon": "^1.17.5",
    "ts-node": "^6.1.0",
    "typescript": "^2.9.1"
  },
  "dependencies": {
    "koa": "^2.5.1"
  }
}

生成tsconfig.json文件

tsc --init

tsconfig.json文件设置如下

{
  "compilerOptions": {
    "outDir": "./dist/",
    "module": "commonjs",
    "noImplicitAny": true,
    "preserveConstEnums": true,
    "sourceMap": true,
    "target": "es5",
    "allowJs": true
  }
}

在根目录下创建 app.ts文件

import * as Koa from 'koa'

const app = new Koa()

app.use(ctx => {
  ctx.body = 'xiadd'
})

app.listen(8002, () => {
  console.log('server is running')
})

输入命令进行编译和运行

npm run build

npm run start

也可以创建run.sh文件 将运行命令写入该文件

nodemon --ext js,ts --exec ts-node dist/app

运行run.sh命令

./run.sh
 

Typescript特点

typescript 通过构造函数的参数直接定义属性,为了证明,我们创建一个info.ts文件 内容如下

class Info {
    constructor(
        public name: string
        private age: number ) {}
}

使用tsc info.ts进行编译后 生成info.js

var Info = /** @class */ (function () {
    function Info(name, age) {
        this.name = name;
        this.age = age;
    }
    return Info;
}());
上一篇下一篇

猜你喜欢

热点阅读