# ts环境搭建
# 安装TS包
cnpm install typescript -g
tsc --version
- 初始化项目:进入编程文件夹后,可以使用npm init -y来初始化项目,生成package.json。
- 创建tsconfig.json文件,在终端中输入tsc --init:它是一个TS项目的配置文件,可以通过读取它来设置TS编译器的编译参数。
- 安装@types/node,使用npm install @types/node --dev-save进行安装。这个主要是解决模块的声明文件问题。
- 编写HelloWorld.ts文件,然后进行保存,代码如下。
var a:string = "HelloWorld"
console.log(a)
cat xxx.xx//可以查看某文件的具体内容,打印在控制台
- 在Vscode的任务菜单下,打开运行生成任务,然后选择tsc:构建-tsconfig.json ,这时候就会生成一个helloWorld.js文件
- 在终端中输入node helloWorld.js就可以看到结果了。
更便捷的安装ts-node,然后使用ts-node启动ts文件
cnpm i ts-node -g
另外ts-node需要依赖 tslib 和 @types/node 两个包:
cnpm install tslib @types/node -g
# TypeScript环境搭建之webpack
- 安装html-webpack-plugin ts-loader typescript cross-env
- tsc init 生成ts.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/main.ts",
output: {
filename: "build.js"
},
resolve: {
extensions: [".tsx", ".ts", ".js"]
},
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 HtmlWebpackPlugin({
template: "./index.html"
})
]
};