经过三期的学习,本篇文章将介绍TS和React/Vue的结合使用,搭载Webpack,助力成长前端高级技术体系。下面继续一起学习:
1.配置TS环境
1.1 使用ts-loader
使用typescript
需要安装ts
相关配置
npm install typescript ts-loader --save-dev
生成ts
的配置文件
npx tsc --init
配置ts-loader
{
test:/\.tsx?/,
use: ['ts-loader'],
exclude: /node_modules/
}
将入口文件更改成ts
文件
let a:string = 'hello';
console.log(a);
执行npm run dev
发现已经可以正常的解析ts
文件啦!
1.2 使用 preset-typescript
不需要借助typescript
npm install @babel/preset-typescript
{
"presets": [
["@babel/preset-env",{
"useBuiltIns":"usage",
"corejs":2
}],
"@babel/preset-react",
["@babel/preset-typescript",{
"allExtensions": true
}]
],
"plugins": [
["@babel/plugin-proposal-decorators", { "legacy": true }],
["@babel/plugin-proposal-class-properties",{"loose":true}],
"@babel/plugin-transform-runtime"
]
}
2.配置ts+react环境
安装react
相关模块
npm i @babel/preset-react --save-dev # 解析jsx语法
npm i react @types/react @types/react-dom react react-dom typescript
import React from 'react';
import ReactDOM from 'react-dom';
const state = {number:0};
type State = Readonly<typeof state>;
class Counter extends React.Component<object,State>{
state:State = state
handleClick =()=>{
this.setState({number:this.state.number+1})
}
render(){
const {number} = this.state;
return (
<div>
<button onClick={this.handleClick}>点击</button>
{number}
</div>
)
}
}
ReactDOM.render(<Counter></Counter>,document.getElementById('root'));
3.配置ts+vue环境
安装vue
所需要的模块
npm install vue-loader vue-template-compiler --save-dev
npm install vue vue-property-decorator
配置ts-loader
{
test: /\.tsx?/,
use: {
loader:'ts-loader',
options: {
appendTsSuffixTo: [/\.vue$/],
},
},
exclude: /node_modules/
}
使用vue-loader
插件
const VueLoaderPlugin = require('vue-loader/lib/plugin');
new VueLoaderPlugin();
配置解析.vue
文件
{
test:/\.vue$/,
use:'vue-loader'
}
增加vue-shims.d.ts
,可以识别.vue
文件
declare module '*.vue' {
import Vue from 'vue';
export default Vue;
}
index.tsx
文件
import Vue from 'vue';
import App from './App.vue';
let vm = new Vue({
render:h=>h(App)
}).$mount('#root')
App.vue文件
<template>
<div>
<div v-for="(todo,index) in todos" :key="index">{{todo}}</div>
</div>
</template>
<script lang="ts">
import {Component,Vue} from 'vue-property-decorator';
@Component
export default class Todo extends Vue{
public todos = ['香蕉','苹果','橘子']
}
</script>
4.配置代理
设置服务端接口
const express = require('express');
const app = express();
app.get('/api/list', (req, res) => {
res.send(['香蕉', '苹果', '橘子']);
});
app.listen(4000);
安装axios
获取数据
npm install axios --save-dev
配置接口请求
<template>
<div>
<div v-for="(todo,index) in todos" :key="index">
{{todo}}
</div>
</div>
</template>
<script lang="ts">
import axios from 'axios';
import {Component ,Vue} from 'vue-property-decorator';
@Component
export default class Todo extends Vue{
public todos:string[] =[];
async mounted(){
let { data } = await axios.get('/api/list');
this.todos = data
}
}
</script>
配置服务器代理路由
proxy: {
'/api': {
target: 'http://localhost:4000',
},
}