typescript的运行环境搭建
方式一: webpack 搭建
-
安装依赖
npm i ts-loader typescript -D -
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' }] } } -
自动生成ts的配置文件
tsconfig.jsontsc --init -
搭建开发环境
- 添加两个依赖
npm i html-webpack-plugin webpack-dev-server -D- 添加
index.html模板文件 - 添加
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
-
搭建环境
npm i ts-node tslib @types/node -g -
我们可以直接通过 ts-node 来运行TypeScript的代码:
ts-node math.ts