第一章、typescript高级


目录
  • 一、typescript语法精讲(一)
    • 1、ts初体验
    • 2、webpack搭建ts环境

一、typescript语法精讲(一)

1、ts初体验
  • IDE语法检测原理
IDE内部会生成代码的AST树,从而分析语法的错误
  • 安装和编译ts
# 安装
npm i -g typescript
# 编译
tsc index.ts
  • ts编译的作用域
* 默认情况下所有ts文件都是在同一作用域下编译的。所以如果存在相同变量名,则编译会有冲突
* 解决冲突方式一:ts文件底部加【export {}】,表示该文件是一个模块(模块有自己的作用域)
  • ts-node搭建ts环境
# 安装
npm i -g ts-node
# 安装依赖
npm i -g tslib @types/node
# 编译并在node环境运行
ts-node index.ts
2、webpack搭建ts环境
  • 安装
npm init -y
npm i -D webpack webpack-cli
npm i -D ts-loader typescript
# 生成tsconfig.json文件
tsc --init
npm i -D webpack-dev-server
npm i -D html-webpack-plugin
  • package.json
{
  "name": "learn-ts",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "serve": "webpack serve"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^5.5.0",
    "ts-loader": "^9.2.9",
    "typescript": "^4.6.4",
    "webpack": "^5.72.0",
    "webpack-cli": "^4.9.2",
    "webpack-dev-server": "^4.8.1"
  }
}
  • webpack.config.js
const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")

module.exports = {
    mode: "development",
    entry: "./src/main.ts",
    output: {
        path: path.resolve(__dirname, "./dist"),
        filename: "bundle.js"
    },
    devServer: {},
    resolve: {
        extensions: [".ts", ".js", ".cjs", ".json"]
    },
    module: {
        rules: [{
            test: /\.ts$/,
            loader: "ts-loader"
        }]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: "./index.html"
        })
    ]
}
  • index.html



    
    ts





  • main.ts
import {sum} from "./math"

const message: string = "黄婷婷"

console.log(sum(20, 30))
console.log(message)
  • math.ts
export function sum(num1: number, num2: number) {
    return num1 + num2
}