typescript 学习笔记

1. 新建文件夹。 crowller

2. 在文件夹下,进行 npm init -y ,进行初始化,出现package.json文件。

3. 在文件夹下,进行 tsc --init , 新增typescript的配置文件 tsconfig.json

4. 安装typescript文件,ts-node工具

npm install typescript --save-dev
npm install ts-node --save-dev

5. 在crowller文件夹下,新建 src文件夹,src文件夹下,新建crowller.ts文件

打开package.json文件,在script{}中,写入命令行 

"scripts": {
    "dev": "ts-node ./src/crowller.ts"
  },

 6. 打开crowller.ts,进行编写代码。

过程中使用到 superagent 这个包,superagent 轻量的Ajax api。

superagent是js编写,在ts语法中直接引入这个类库,ts不知道这个类库会有什么方法。所以需要安装一个类型定义文件 *.d.ts :npm i @types/superagent
npm i superagent --save
npm i @types/superagent
import superagent from 'superagent' 
class Crowller {
  private _url: string;
  private rowHtml = '';
  constructor(url:string){
    this._url = url;
    this.getRawHtml();
  };
  async getRawHtml(){
    const result = await superagent.get(this._url)
    this.rowHtml = result.text
  console.log(this.rowHtml);
  }
  get url(){
    return this._url
  }
  set url(url){
    this._url = url
  }

}

const r = new Crowller('https://www.cnblogs.com/shine-lovely/p/12777684.html')

7. 在终端中运行 npm run dev

原文地址:https://www.cnblogs.com/shine-lovely/p/14121218.html