众所周知 typescript 是javascript的一个超集,扩展了js的功能
更加的严格的一种语法,阿里的前端开发就是采用的ts开发的
ts开发项目能在开发阶段发现90%的问题 往后 ts也必将成为主流
vue3.0也慢慢开始支持ts了
1.好了废话不多说了 还是 直接上代码了
安装依赖
npm install typescript awesome-typescript-loader -D
在项目根目录下 新建立一个 tsconfig.js文件
{
"compilerOptions":{
"module":"commonjs",//编译的代码采用的模块规范
"target":"es5",// 编译出的代码采用es的那个版本,
"sourceMap":true, //输出Source Map以方便调试
"importHelpers":true // 减少辅助函数的输出 缩小压缩后的代码体积
},
"exclude":{// 不编译下面这些目录中的文件
"node_modules"
}
}
2.在src新建立一个 demo.ts文件
export function show(content:string){
window.document.getElementById('app').innerText="Hello,"+content;
}
3.在src/index.js文件中引入
import { show } from "./demo.ts"
show('webpack');
4.在webpack.config.js文件中配置
module:{
rules:[
{
test:/\.ts$/,
use:['awesome-typescript-loader'],
exclude:/node_modules/
}
]
}
5.别忘了在html文件中 注册 一个
<div id="app"></div>
6.最后我们运行看看 页面上正常显示
7.附上webpack.config.js的整个配置
const path=require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin');
const {CleanWebpackPlugin}=require('clean-webpack-plugin');
module.exports={
mode:'development',
entry:"./src/index.js",
output:{
filename:'bundle.min.js',
path:path.resolve(__dirname,'dist/')
},
module:{
rules:[
{
test:/\.js$/,
use:['babel-loader'],
exclude:/node_modules/
},
{
test:/\.ts$/,
use:['awesome-typescript-loader'],
exclude:/node_modules/
}
]
},
resolve:{
extensions:['.ts','.js','.sass','.css']
},
devServer:{
open:true,
// cache:false,
// port:8080,
// hot:true,
contentBase:'dist/'
},
// 输出souce-map 方便调试 es6的源码
devtool:'source-map',
plugins:[
new HtmlWebpackPlugin({
template:path.join(__dirname,'/index.html')
}),
new CleanWebpackPlugin()
]
}
8.还有package.json文件
{
"name": "typescript",
"version": "1.0.0",
"description": "",
"main": "tsconfig.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"dev": "webpack-dev-server"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.8.7",
"@babel/preset-env": "^7.8.7",
"awesome-typescript-loader": "^5.2.1",
"babel-loader": "^8.0.6",
"clean-webpack-plugin": "^3.0.0",
"html-webpack-plugin": "^3.2.0",
"typescript": "^3.8.3",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
}
}
好了 这下 就完了 就能支持 typescript了 如果能帮到你 我会很高兴的 觉有有用的话点个赞
生活那么苦,为啥不给自己一颗糖吃呢!坚持下去!你会看到不一样的风景!加油 奥利给!