初识TypeScript

145 阅读1分钟

安装

npm install -g typescript

查看版本

tsc -v

手动编译ts文件

tsc helloworld.ts

vscode自动编译ts文件

  • 生成配置文件tsconfig.json
 tsc --init
  • 修改tsconfig.json配置
"outDir": "./js",
"strict": false, 
  • 启动监视任务
终端 -> 运行任务 -> 监视tsconfig.json

在node环境下运行ts文件的配置

//安装
npm i @types/node --save-dev
npm i ts-node --g

//查看版本号
ts-node -v

//运行文件
ts-node helloworld.ts

使用webpack打包ts

  1. 生成package.json
npm init -y
  1. 生成tscconfig.json
tsc --init
  1. 下载依赖的包(注意版本号)
npm install -D typescript
npm install -D webpack@4.41.5 webpack-cli@3.3.10
npm install -D webpack-dev-server@3.10.2
npm install -D html-webpack-plugin clean-webpack-plugin
npm install -D ts-loader@8.0.11
npm install -D cross-env
  1. 配置打包目录
"dev": "cross-env NODE_ENV=development webpack-dev-server --config build/webpack.config.js",
"build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
  1. 运行项目
npm run dev 
  1. webpack.config.js
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')

const isProd = process.env.NODE_ENV === 'production' // 是否生产环境

function resolve (dir) {
  return path.resolve(__dirname, '..', dir)
}

module.exports = {
  mode: isProd ? 'production' : 'development',
  entry: {
    app: './src/main.ts'
  },

  output: {
    path: resolve('dist'),
    filename: '[name].[contenthash:8].js'
  },

  module: {
    rules: [
      {
        test: /.tsx?$/,
        use: 'ts-loader',
        include: [resolve('src')]
      }
    ]
  },

  plugins: [
    new CleanWebpackPlugin({}),

    new HtmlWebpackPlugin({
      template: './public/index.html'
    })
  ],

  resolve: {
    extensions: ['.ts', '.tsx', '.js']
  },

  devtool: isProd ? 'cheap-module-source-map' : 'cheap-module-eval-source-map',

  devServer: {
    host: 'localhost',    // 主机名
    stats: 'errors-only', // 打包日志输出输出错误信息
    port: 8081,
    open: true
  },
}
  1. package.json中依赖名称与版本号
"clean-webpack-plugin": "^3.0.0",
"cross-env": "^7.0.2",
"html-webpack-plugin": "^4.5.0",
"ts-loader": "^8.0.11",
"typescript": "^4.0.5",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.2"