开始编写Typescript
新建一个文件夹
touch typescript-learn
npm init -y
npm i typescript --location
查看tsc 的一些配置
tsc -h
初始化ts配置
tsc --init
查看tsconfig.json文件
创建一个ts文件
touch src
cd src
mkdir index.ts
用tsc编译这个文件
tsc ./src/index.ts
编译出的js文件就在当前目录下
使用webpack5来方便编译ts文件
创建build文件夹并且创建config文件
- webpack.config.js
// 主配置文件
const { merge } = require('webpack-merge'); // 合并配置
const baseConfig = require('./webpack.base.config');
const devConfig = require('./webpack.dev.config');
const proConfig = require('./webpack.pro.config');
module.exports = (env,argv) => {
let config = argv.mode === 'development' ? devConfig : proConfig
return merge(baseConfig, config)
}
- webpack.base.config.js
// webpack.base.config.js 通用配置
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry:'./src/index.ts',
output:{
filename:'app.js'
},
resolve:{
extensions:['.js', '.ts', '.tsx'], // 指定相关拓展名
},
module:{
rules:[
{
test:/\.tsx?$/i,
use:[{
loader:'ts-loader'
}],
exclude:/node_modules/
}
]
},
plugins:[
new HtmlWebpackPlugin({ // 通过一个模板帮助我们生成网站的首页,把输出文件自动嵌入到这个文件中
template:'./src/tpl/index.html'
})
]
}
- webpack.dev.config.js
// 开发环境配置
module.exports = {
devtool:'eval-cheap-module-source-map', // 开启source map
}
- webpack.pro.config.js
// 生产环境配置
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
plugins: [
new CleanWebpackPlugin() // 构建成功后,帮助清空dist目录
]
}
安装相关npm包和配置命令
- package.json
{
"name": "typescript-learn",
"version": "1.0.0",
"description": "",
"main": "src/index.ts",
"scripts": {
"start": "webpack serve --mode development --env development --config ./build/webpack.config.js",
"build": "webpack --mode production --env production --config ./build/webpack.config.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^4.0.0",
"html-webpack-plugin": "^5.5.0",
"ts-loader": "^9.3.1",
"typescript": "^4.8.2",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.10.1",
"webpack-merge": "^5.8.0"
}
}
创建index.html
- index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Typecript temp</title>
</head>
<body>
<div class="app"></div>
</body>
</html>
启动 npm run start
在浏览器访问http://localhost:8080/,此时是空白的
修改index.ts
let hello:string = 'Hello Typescript'
document.querySelectorAll('.app')[0].innerHTML = hello;
再次访问http://localhost:8080/
打个包npm run build 看一下输出
dist文件夹也出现了
公众号
欢迎大家关注我的公众号: 石马上coding,一起成长