vue+typescript组建前端架构

第一步、安装vue 


npm install -g vue-cli


第二步、创建vue项目


vue init webpack XXX项目

cd XXX项目


第三步、安装依赖


npm install typescript vue-class-component -D

npm install [email protected] -D


第四步、修改webpack配制文件


然后修改 ./build/webpack.base.conf.js 文件中,在 resolve.extension 中添加 ‘.ts’,使引入 ts 文件时不用写 .ts 后缀

在 module.rules 中添加 webpack 对 ts 文件的解析

{

test: /\.tsx?$/,

loader: 'ts-loader',

exclude: /node_modules/,

options: {

appendTsSuffixTo: [/\.vue$/]

}

}


第五步、增加typescript配制文件


在项目根目录下创建 tsconfig.json 文件:

// tsconfig.json

{

"compilerOptions": {

// 与 Vue 的浏览器支持保持一致

"target": "es5",

// 这可以对 `this` 上的数据属性进行更严格的推断

"strict": true,

// 如果使用 webpack 2+ 或 rollup,可以利用 tree-shake:

"module": "es2015",

"moduleResolution": "node",

// 允许从没有设置默认导出的模块中默认导入

"allowSyntheticDefaultImports": true,

// 启用装饰器

"experimentalDecorators": true

}

}


第六步、vue-shim.d.ts 文件


在 ./src 目录创建 vue-shim.d.ts 文件,让 ts 识别 .vue 文件:

// vue-shim.d.ts

declare module "*.vue" {

import Vue from "vue";

export default Vue;

}


第七步、修改vue文件


将 src 目录下的所有 js 文件后缀改为 .ts,然后将 webpack 配置文件 ./build/webpack.base.conf.js 中的入口 entry 修改为 main.ts

改造之后的 ts 文件不会识别 .vue 文件,所以在引入 .vue 文件的时候,需要手动添加 .vue 后缀 ,在所有 .vue 文件中,都需要在 中添加 lang="ts" 标识

在命令行使用npm run dev 不报错就成功


第八步、利用 vue-class-component 继续改造

然后改造 .vue 文件的 部分,以 HelloWorld.vue 为例:

import Vue from 'vue'

import Component from 'vue-class-component'

// @Component 修饰符注明了此类为一个 Vue 组件

@Component({})

export default class Hello extends Vue {

msg: String = 'Welcome to Your Vue.js App'

}

你可能感兴趣的:(vue+typescript组建前端架构)