当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 如何用vue-cli3脚手架搭建一个基于ts的基础脚手架的方法

如何用vue-cli3脚手架搭建一个基于ts的基础脚手架的方法

2020年03月09日  | 移动技术网IT编程  | 我要评论

忙里偷闲,整理了一下关于如何借助 vue-cli3 搭建 ts + 装饰器 的脚手架,并如何自定义 webpack 配置,优化。

准备工作

  • @vue/cli@4.1.1
  • vue 2.6
  • node v12.13.0

安装 node

  • 安装 node
  • 全局安装 nrm,npm 的镜像源管理工具。
npm i nrm -g // 安装
nrm ls // 查看可用源,及当前源,带*的是当前使用的源
nrm use taobao // 切换源,使用源
nrm add <registry> <url> // 其中reigstry为源名,url为源的路径
nrm del <registry> // 删除对应的源
nrm test npm // 测试源的响应速度

安装 vue-cli3

参考官方文档:

npm i @vue/cli -g // 全局安装

vue --version // 检查是否安装

补充

npm list -g --depth 0 // 查看全局安装的包
npm outdated -g --depth=0 // 查看需要更新的全局包
npm update 包名 -g // 更新全局安装的包

搭建项目

可参考:使用vue-cli 3.0搭建vue项目

新建一个基于 ts 的 vue 项目

vue create vue-cli3-ts

备注:如果是 window 系统,用 git bash 交互提示符(切换)不会工作,用以下命令,即可解决:

winpty vue.cmd create vue-cli3-ts
  • 自定义选项 - manually select features
  • 添加 ts 支持 - typescript
  • 基于类的组件 - y
  • tslint
  • 根据需要添加 router、vuex、css(less 或 scss) 预处理器、单元测试(jest)

交互说明:

  • 上下箭头键切换
  • 空格键选中
  • 回车确定

在已存在的项目中添加 ts

vue add @vue/typescript

会把所有 .js 更改为 .ts

script 命令

// - 启动服务
npm run serve
// - 打包编译
npm run build
// - 执行lint
npm run lint
// - 执行单元测试
npm run test:unit

npm run serve 启动服务:http://localhost:8080/#/

vue 中 ts 语法

demo: src/components/helloworld.vue

<script lang="ts">
import { component, prop, vue } from 'vue-property-decorator';

@component
export default class helloworld extends vue {
 @prop() private msg!: string;
}
</script>

和普通的 vue 项目不一样的就是.vue 文件中 script 的 写法。

主要用到的一个库:vue-property-decorator

用法可参考:

1. 类型注解,类型推论

  • 变量后面通过 冒号+类型 来做类型注解。
  • 编译时类型检查,写代码时代码提醒。
  • 类型推论,根据赋值类型推论出被赋值变量的类型,进行类型限制。
let title: string; // 类型注解
title = 'ts'; // 正确
title = 4; // 错误

let text = 'txt'; // 类型推论
text = 2; // 错误

错误时,vscode 编辑器会有红色波浪号提示。

数组

let names: string[]; // array<string>
names = ['tom'];

任意类型,没有类型限制

let foo: any;
foo = 'foo';
foo = 3;

let list: any[];
list = [1, true, 'free'];
list[1] = 100;

函数中使用类型

function greeting (person: string): string {
 return 'hello, ' + person;
}

// void 类型,常用于没有返回值的函数
function warnuser (): void {
 alert('this is msg');
}

案例:vue demo

<template>
 <div class="hello">
 <input type="text" placeholder="请输入新特性" @keyup.enter="addfeature" />
 <ul>
 <li v-for="feature in features" :key="feature">{{feature}}</li>
 </ul>
 </div>
</template>

<script lang="ts">
import { component, prop, vue } from 'vue-property-decorator';

@component
export default class demo extends vue {

 // 相当于 data 中的数据项
 features: string[];
 constructor () {
 super();
 this.features = ['类型注解', '类型推论', '编译型语言'];
 }

 // 相当于 methods 中的方法
 addfeature (event: any) {
 console.log(event);
 this.features.push(event.target.value);
 event.target.value = '';
 }
}
</script>

2.类

ts 中的类和 es6 中的大体相同,关注特性 访问修饰符

  • private 私有属性,不能在类的外部访问
  • protected 保护属性,可以在类的内部和派生类的内部访问,不能在类的外部访问
  • public 公有属性,可以在任意地方访问,默认值
  • readonly 只读属性,必须在声明时或构造函数里初始化,不可改变值

构造函数:初始化成员变量,参数加上修饰符,能够定义并初始化一个属性

constructor (private name = 'tom') {
 super();
}

等同于

name: string;
constructor () {
 super();
 this.name = 'tom';
}

存取器,暴露存取数据时可添加额外逻辑;在 vue 中可用作计算属性

get fullname () { return this.name; }
set fullname (val) { this.name = val; }

案例:vue demo

<template>
 <p>特性数量:{{count}}</p>
</template>
<script lang="ts">
 export default class demo extends vue {
 // 定义 getter 作为计算属性
 get count () {
  return this.features.length;
 }
 }
</script>

接口

接口仅约束结构,不要求实现

interface person {
 firstname: string;
 lastname: string;
}
function greeting (person: person) {
 return `hello, ${person.firstname} ${person.lastname}`;
}
const user = {firstname: 'jane', lastname: 'user'};
console.log(greeting(user));

案例:vue demo,声明接口类型约束数据结构

<template>
 <li v-for="feature in features" :key="feature.id">{{feature.name}}</li>
</template>
<script lang="ts">
 // 定义一个接口约束feature的数据结构
 interface feature {
 id: number;
 name: string;
 }
 
 export default class demo extends vue {
 private features: feature[];
 
 constructor () {
  super();
  
  this.features = [
  {id: 1, name: '类型注解'},
  {id: 2, name: '类型推论'},
  {id: 3, name: '编译型语言'}
  ]
 }
 }
</script>

泛型

泛型 是指在定义函数、接口或类的时候,不预先指定具体的类,而是在使用时才指定类型的一种特性。

interface result<t> {
 data: t;
}

// 不使用泛型
interface result {
 data: feature[];
}

案例:使用泛型约束接口返回类型

function getdata<t>(): result<t> {
 const data: any = [
 {id: 1, name: '类型注解'},
 {id: 2, name: '类型推论'},
 {id: 3, name: '编译型语言'} 
 ];
 return {data};
}

// 调用
this.features = getdata<feature[]>().data;

案例:使用泛型约束接口返回类型 promise

function getdata<t>(): promise<result<t>> {
 const data: any = [
 {id: 1, name: '类型注解'},
 {id: 2, name: '类型推论'},
 {id: 3, name: '编译型语言'} 
 ];
 return promise.resolve<result<t>>({data});
}

// 调用 async 方式
async mounted () {
 this.features = (await getdata<feature[]>()).data;
}

// 调用 then 方式
mouted () {
 getdata<feature[]>().then((res: result<feature[]>) => {
 this.features = res.data;
 })
}

装饰器

装饰器用于扩展类或者它的属性和方法。

属性声明:@prop

除了在 @component 中声明,还可以采用@prop的方式声明组件属性

export default class demo extends vue {
 // props() 参数是为 vue 提供属性选项
 // !称为明确赋值断言,它是提供给ts的
 @prop({type: string, require: true})
 private msg!: string;
}

事件处理:@emit

// 通知父类新增事件,若未指定事件名则函数名作为事件名(驼峰变中划线分隔)
@emit()
private addfeature(event: any) {// 若没有返回值形参将作为事件参数
 const feature = { name: event.target.value, id: this.features.length + 1 };
 this.features.push(feature);
 event.target.value = "";
 return feature;// 若有返回值则返回值作为事件参数
}

template 模板组件上正常写,@add-feature

变更监测:@watch

@watch('msg')
onroutechange(val:string, oldval:any){
 console.log(val, oldval);
}

装饰器原理

装饰器本质是工厂函数,修改传入的类、方法、属性等

类装饰器

// 类装饰器表达式会在运行时当作函数被调用,类的构造函数作为其唯一的参数。
function log(target: function) {
 // target是构造函数
 console.log(target === foo); // true
 target.prototype.log = function() {
 console.log(this.bar);
}
// 如果类装饰器返回一个值,它会使用提供的构造函数来替换类的声明。
}
@log
class foo {
 bar = 'bar'
}
const foo = new foo();
// @ts-ignore
foo.log();

实战一下 component,新建 decor.vue

<template>
 <div>{{msg}}</div>
</template>
<script lang='ts'>
 import { vue } from "vue-property-decorator";
 function component(options: any) {
 return function(target: any) {
  return vue.extend(options);
 };
 }
 
 @component({
 props: {
  msg: {
  type: string,
  default: ""
  }
 }
 })
 export default class decor extends vue {}
</script>

源码简单了解

类装饰器主要依赖库:vue-class-component,深入源码,了解其背后究竟做了什么。

vue-property-decorator.js

import vue from 'vue';
import component, { createdecorator, mixins } from 'vue-class-component';
export { component, vue, mixins as mixins };

createdecorator、applymetadata 是核心,后续实现都依赖它,比如 prop、watch、ref。

prop 源码实现:

export function prop(options) {
 if (options === void 0) { options = {}; }
 return function (target, key) {
 applymetadata(options, target, key);
 createdecorator(function (componentoptions, k) {
  ;
  (componentoptions.props || (componentoptions.props = {}))[k] = options;
 })(target, key);
 };
}

applymetadata,见名知义,就是将装饰器中的信息拿出来放到 options.type 中。

/** @see {@link https://github.com/vuejs/vue-class-component/blob/master/src/reflect.ts} */
var reflectmetadataissupported = typeof reflect !== 'undefined' && typeof reflect.getmetadata !== 'undefined';
function applymetadata(options, target, key) {
 if (reflectmetadataissupported) {
 if (!array.isarray(options) &&
  typeof options !== 'function' &&
  typeof options.type === 'undefined') {
  options.type = reflect.getmetadata('design:type', target, key);
 }
 }
}

reflect.getmetadata 获取设置在类装饰器上的元数据。可参考文章理解:

createdecorator,见名知义,就是创建装饰器。本质是在类上定义一个私有属性

export function createdecorator(factory) {
 return function (target, key, index) {
 var ctor = typeof target === 'function'
  ? target
  : target.constructor;
 if (!ctor.__decorators__) {
  ctor.__decorators__ = [];
 }
 if (typeof index !== 'number') {
  index = undefined;
 }
 ctor.__decorators__.push(function (options) { return factory(options, key, index); });
 };
}

项目代理及 webpack 性能优化

在项目根目录下新建 vue.config.js

本地开发 api 代理

module.exports = {
 devserver: {
 proxy: {
  '/api': {
  target: '<url>',
  changeorigin: true,
  pathrewrite: {
  '^/api': ''
  }
  }
 }
 }
}

本地开发 api 模拟

devserver: {
 before (app) {
 before (app) {
  app.get('/api/getlist', (req, res) => {
  res.json({data: [{id: 1, name: 'vue'}]})
  })
 }
 }
}

性能优化

查看打包依赖

在 package.json 文件 script 中加入命令:

"build:report": "vue-cli-service build --report"

会在 dist 目录下生成 report.html,可直接打开,查看打包依赖,进行分析,进行打包优化

打包优化 - cdn 引入公共库

在 vue.config.js 中加入配置:

configurewebpack: {
 externals: { // cdn 外链,避免包太大,首屏优化
 'vue': 'vue',
 'vue-router': 'vuerouter',
 'vuex': 'vuex'
 }
}

在 public/ 中加入 cdn 库地址

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.1.3/vue-router.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.2/vuex.min.js"></script>

<!-- built files will be auto injected -->

再次优化,html head 信息中加,dns 域名预解析,js 库 reload 预加载。

<link rel="dns-prefetch" href="cdnjs.cloudflare.com" rel="external nofollow" >
<link href="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js" rel="preload" as="script">
<link href="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.1.3/vue-router.min.js" rel="preload" as="script">
<link href="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.2/vuex.min.js" rel="preload" as="script">

其他

修改本地开发端口号,在 vue.config.js 中加入配置:

devserver: {
 port: 8888
}

体验优化-打包完成提示:

const webpackbuildnotifierplugin = require('webpack-build-notifier');
const path = require('path');

module.exports = {
 // 链式操作
 chainwebpack: config => {
 // 移除 prefetch 插件,移动端对带宽敏感
 // 路由懒加载,只对用户频繁操作的路由,通过 注释 提前获取
 // component: () => import(/* webpackchunkname: "about" */ /* webpackprefetch: true */'../views/about.vue')
 config.plugins.delete('prefetch');
 
 // 生产打包才提示,开发不提示
 if (process.env.node_env === 'production') {
  config.plugin('build-notify').use(webpackbuildnotifierplugin, [{
  title: "my project webpack build",
  logo: path.resolve("./img/favicon.png"),
  suppresssuccess: true
  }])
 }
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网