ts 环境搭建

1,npm 配置

  • # 在空文件夹下初始化,生成package.json 文件
    npm init 
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16

    - 配置 package.json

    ```json
    {
    "name": "module",
    "version": "1.0.0",
    "description": "",
    "main": "index.ts", //入口文件
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC"
    }

2,ts初始化

1
2
3
# 在文件夹下生成 tsconfig.json 配置文件
npm i typescript tslint -g
tsc --init

3,webpack配置

  • 安装依赖库

    1
    2
    3
    4
    # 安装webpack相关依赖
    npm install webpack webpack-cli webpack-dev-server -D
    npm i cross-env ts-loader clean-webpack-plugin html-webpack-plugin -D
    npm i typescript
  • 配置webpack-config.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    const HtmlWebpackPlugin = require("html-webpack-plugin")
    const {CleanWebpackPlugin} = require("clean-webpack-plugin")

    module.exports = {
    entry: "./src/index.ts",
    output: {
    filename: "main.js",
    },
    resolve:{
    extensions: ['.js','.ts','.tsx']
    },
    module:{
    rules:[{
    test: /\.tsx?$/,
    use: 'ts-loader',
    exclude: /node_modules/
    }]
    },
    devtool: process.env.NODE_ENV === 'production' ? false : "inline-source-map",
    devServer:{
    contentBase: "./dist",
    stats: "errors-only",
    compress: false,
    host: 'localhost',
    port: 8080,
    },
    plugins:[
    new CleanWebpackPlugin({
    cleanOnceBeforeBuildPatterns: ['./dist'] // 生成文件前先清空dis文件夹
    }),
    new HtmlWebpackPlugin({ //html模版
    template: "./src/template/index.html"
    })
    ]

    }

4,tslint 代码规范配置

  • tslint.json 生成tslint.json文件

    1
    tslint -i
  • 配置tslint.json

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    {
    "defaultSeverity": "error",
    "extends": [
    "tslint:recommended"
    ],
    "jsRules": {},
    "rules": {
    "no-console": false
    },
    "rulesDirectory": []
    }
  • 配置vscode文件

    • 安装vscode 关于tslint的插件

      TSLint TSlint(deprecated) TSLint Snipeets

    • 配置vscode setting.json 文件

      打开vscode-> 首选项->设置->settings.json, 使能配置自动完善ts错误

      1
      2
      3
      {
      "tslint.autoFixOnSave": true,
      }