学习typescript时候,本地环境的搭建

88 阅读1分钟

typescript的运行环境搭建

方式一: webpack 搭建

  1. 安装依赖

    npm i ts-loader typescript -D
    
  2. webpack添加如下配置:

    const path = require('path')
    module.exports = {
      mode: "development", // webpack 模式
      entry: "./src/main.ts",
      output: {
        path: path.resolve(__dirname, "./dist"),
        filename: "bundle.js"
      },
      resolve: {
        extensions: [".ts", ".js", ".cjs", ".json"] // 添加后缀的处理
      },
      module: {
        rules: [{ test: /.ts$/, loader: 'ts-loader' }]
      }
    }
    
  3. 自动生成ts的配置文件 tsconfig.json

    tsc --init
    
  4. 搭建开发环境

    1. 添加两个依赖
    npm i html-webpack-plugin webpack-dev-server -D
    
    1. 添加 index.html模板文件
    2. 添加webpack配置
    const path = require('path')
    + const HtmlWebpackPlugin = require('html-webpack-plugin')
    ​
    module.exports = {
      mode: "development", // webpack 模式
      entry: "./src/main.ts",
      output: {
        path: path.resolve(__dirname, "./dist"),
        filename: "bundle.js"
      },
      resolve: {
        extensions: [".ts", ".js", ".cjs", ".json"] // 添加后缀的处理
      },
      module: {
        rules: [{ test: /.ts$/, loader: 'ts-loader' }]
      },
    + devServer: {},
    + plugins: [
    +   new HtmlWebpackPlugin({
    +     template: "./index.html"
    +   })
    + ]
    }
    

方式二: ts-node

  1. 搭建环境

    npm i ts-node tslib @types/node -g
    
  2. 我们可以直接通过 ts-node 来运行TypeScript的代码:

    ts-node math.ts