TS安装
$ npm install -g typescript
$ tsc -V
Version 4.1.5
手动编译代码
我们使用了 .ts
扩展名,但是这段代码仅仅是 TypeScript,并不能在浏览器直接运行,需要将TypeScript转为JavaScript。
在命令行上,运行 TypeScript 编译器:
tsc helloworld.ts
输出结果为一个 helloworld.js
文件,它包含了和输入文件中相同的 JavaScript 代码。
webstorm自动编译
webpack打包TS
创建相关文件
localhost:ts-study cuiliang$ tree .
.
├── build
│ └── webpack.config.js
├── public
│ └── index.html
└── src
└── main.ts
3 directories, 3 files
- 入口JS: src/main.ts ```typescript class Greeter { greeting: string; constructor(message: string){ this.greeting = message; } greet(){ return “Hello,” + this.greeting; } }
let greeter = new Greeter(“World”); alert(greeter.greet())
- index页面: public/index.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>webpack & TS</title>
</head>
<body>
</body>
</html>
webpack配置文件:webpack.config.js
const path = require('path');
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'production',
entry: './src/main.ts',
module: {
rules: [{
// 对后缀是.ts的文件操作
test: /\.ts?$/,
// 利用ts-loader
use: 'ts-loader',
// 不对node_modules操作
exclude: /node_modules/
}]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new CleanWebpackPlugin({}),
new HtmlWebpackPlugin({
template: './public/index.html'
})
],
devServer: {
host: 'localhost', // 主机名
stats: 'errors-only', // 打包日志输出输出错误信息
port: 8080,
open: true
},
}
npm初始化项目
```bash localhost:ts-study cuiliang$ npm init -y Wrote to /Users/cuiliang/WebstormProjects/ts-study/package.json:
{ “name”: “ts-study”, “version”: “1.0.0”, “description”: “”, “main”: “index.js”, “scripts”: { “test”: “echo \”Error: no test specified\” && exit 1” }, “keywords”: [], “author”: “”, “license”: “ISC” }
<a name="Gdf3x"></a>
### 初始化ts配置文件
```bash
localhost:ts-study cuiliang$ tsc --init
message TS6071: Successfully created a tsconfig.json file.
localhost:ts-study cuiliang$ tree .
.
├── package-lock.json
├── package.json
├── public
│ └── index.html
├── src
│ └── main.ts
├── tsconfig.json
└── webpack.config.js
3 directories, 5 files
下载依赖
npm install -D typescript
npm install -D webpack@4.41.5 webpack-cli@3.3.10 webpack-dev-server@3.10.2
npm install -D html-webpack-plugin@4.0.0 clean-webpack-plugin@3.0.0
npm install -D ts-loader
修改ts配置(tsconfig.json)
// 禁用严格校验模式
"strict": false,
配置打包命令(package.json)
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"server": "webpack-dev-server --open",
"build": "npm run build"
}
运行与打包
npm server
npm build