往期回顧:
從0搭建本身的webpack開發環境(一)
從0搭建本身的webpack開發環境(二)
從0搭建本身的webpack開發環境(三)javascript
通過三期的學習,本篇文章將介紹TS和React/Vue的結合使用,搭載Webpack,助力成長前端高級技術體系。下面繼續一塊兒學習:html
使用typescript
須要安裝ts
相關配置前端
npm install typescript ts-loader --save-dev
生成ts
的配置文件vue
npx tsc --init
配置ts-loader
java
{ test:/\.tsx?/, use: ['ts-loader'], exclude: /node_modules/ }
將入口文件更改爲ts
文件node
let a:string = 'hello'; console.log(a);
執行npm run dev
發現已經能夠正常的解析ts
文件啦!react
不須要藉助typescript
webpack
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" ] }
安裝react
相關模塊ios
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'));
安裝vue
所須要的模塊web
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>
設置服務端接口
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', }, }
有什麼你想知道的前端知識,歡迎添加微信留言:webyouxuan