vue init webpack '項目名稱'
cnpm i typescript ts-loader --save-dev
注意:這兩個是配置typescript必須的文件,後面一步一步深刻咱們會安裝更多插件。vue
打開build/webpack.base.config.jsnode
entry: { app: './src/main.ts' // 修改main.js 爲main.ts後面會提到main.ts } resolve: { ... extensions: ['.js', '.ts', '.tsx', '.vue', '.json'] // 新增ts tsx ... }, module: { rules: [ { test: /\.ts$/, exclude: /node_modules/, enforce: 'pre', loader: 'tslint-loader' }, { test: /\.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, options: { appendTsSuffixTo: [/\.vue$/], } }, ] // 添加ts、tsx解析配置
{ "include": [ "./src/**/*" ], "exclude": [ "node_modules" ], "compilerOptions": { "allowSyntheticDefaultImports": true, "experimentalDecorators": true, "strict": true, "allowJs": true, "module": "es2015", "target": "es5", "moduleResolution": "node", "isolatedModules": true, "lib": [ "dom", "es5", "es2015.promise" ], "sourceMap": true, "pretty": true } }
declare module "*.vue" { import Vue from "vue"; export default Vue; }
main.js => main.ts
router/index.js => index.ts
main.ts中 import App from './App' => import App from './App.vue' router/index.js中 import HelloWorld from '@/components/HelloWorld' 修改成 import Helloworld from '@/components/HellowWorld.vue'
注意:原來import的文件都必須加上.vue後綴webpack
<script lang="ts"> import Vue from 'vue' export default Vue.extend({ name: 'HelloWorld', data () { return { msg: 'Welcome to Your Vue.js App' } } }) </script>
這裏作了初步修改,後面咱們會使用插件vue-class-component進行修改,若是寫過angular2+那麼就很容易上手git
npm run dev
若是運氣好,那麼項目就這麼啓動了。github
問題1:web
vue typescript Module build failed: Error: You may be using an old version of webpack; please check you're using at least version 4
解決:package.json 中修改ts-loader版本爲3.5,而後cnpm install 最後從新啓動 npm run dev 就行了。vuex
問題2:typescript
TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig' to remove this warning.
解決:.tsconfig.json 中缺乏配置 "experimentalDecorators": truenpm
cnpm i vue-class-component --save-dev
<template> <div class="hello"> <h1>{{ msg }}</h1> </div> </template> <script lang="ts"> import Vue from 'vue' import Component from 'vue-class-component' @Component({ // 屬性 props props: { propMessage: String } }) export default class HelloWorld extends Vue { // data 初始化變量 msg: string = 'typescript learn' list: string[] = [] // hook 生命週期函數 mounted () { console.log('mounted') } // computed 計算屬性 get computedMsg () { return this.msg + 'computed' } set computedMsg (val) { console.log(val) } // method 方法 showList () { this.list.push('nihao') } } </script> <style scoped> </style>
插件地址:https://github.com/vuejs/vue-...
github項目地址:https://github.com/zxc1989092...json
cnpm i vue-property-decorator --save-dev
github地址:https://github.com/kaorun343/...
待續......