初始化项目
进入项目的根目录,执行命令
npm init -y
作用:创建package.json文件
下载构建工具
npm i -D webpack webpack-cli webpack-dev-server typescript ts-loader clean-webpack-plugin
共安装了7个包
webpack
构建工具webpack
webpack-cli
webpack的命令行工具
webpack-dev-server
webpack的开发服务器
typescript
ts编译器
ts-loader
ts加载器,用于在webpack中编译ts文件
html-webpack-plugin
webpack中html插件,用来自动创建html文件
clean-webpack-plugin
webpack中的清除插件,每次构建都会先清除目录
根目录下创建webpack的配置文件webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
optimization:{
minimize: false // 关闭代码压缩,可选
},
entry: "./src/index.ts",
devtool: "inline-source-map",
devServer: {
contentBase: './dist'
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
environment: {
arrowFunction: false // 关闭webpack的箭头函数,可选
}
},
resolve: {
extensions: [".ts", ".js"]
},
module: {
rules: [
{
test: /\.ts$/,
use: {
loader: "ts-loader"
},
exclude: /node_modules/
}
]
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title:'TS测试'
}),
]
}
根目录下创建tsconfig.json
{
"compilerOptions": {
"target": "ES2015",
"module": "ES2015",
"strict": true
}
}
修改package.json的配置(相应位置加入)
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack serve --open chrome.exe"
},
在src下创建ts文件,并在并命令行执行npm run build对代码进行编译,或者执行npm start来启动开发服务器。
const bol: boolean = true
const num: number = 1024
console.log(num)
const userName: string = "hhh"
//字符串模板依旧能用
const str:string=`${userName}`
console.log(userName)