Home  >  Article  >  Web Front-end  >  Practical combat with Vue+TypeScript project configuration

Practical combat with Vue+TypeScript project configuration

藏色散人
藏色散人forward
2020-06-12 13:20:472815browse

The following js tutorial column will introduce to you how to use Vue TypeScript project configuration in practice. I hope it will be helpful to friends in need!

Using Vue TypeScript project configuration practice

Project construction

Building through scaffolding

1. Create a vue project through Vue CLI 3

vue create vue-typescript
// 在此选择typescript支持
? Check the features needed for your project: () Babel () TypeScript ( ) Progressive Web App (PWA) Support () Router () Vuex >() CSS Pre-processors () Linter / Formatter ( ) Unit Testing ( ) E2E Testing 我是08年出道的高级前端架构师,有问题或者交流经验可以进我的扣扣裙 519293536 我都会尽力帮大家哦
// 引入 vue-class-component 插件 // 以下大概是我的选择 ? Use class-style component syntax? (Y/n) y ? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? Yes ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with node-sass) ? Pick a linter / formatter config: Prettier ? Pick additional lint features: Lint on save ? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files ? Save this as a preset for future projects? (y/N) n

Related recommendations: "js Advanced Tutorial"

2. Start the project

yarn run serve

Can it run? If it can run, it is a good project

3. Project configuration

At this point, the scaffolding has actually helped us configure most of the configuration, but we still need to be familiar with the configuration. .

tsconfig.json

Create tsconfig.json in the project root directory.

{
  // 编译选项
  "compilerOptions": {
    // 输出目录
    "outDir": "./output",
    // 是否包含可以用于 debug 的 sourceMap
    "sourceMap": true,
    // 以严格模式解析
    "strict": true,
    // 采用的模块系统
    "module": "esnext",
    // 如何处理模块
    "moduleResolution": "node",
    // 编译输出目标 ES 版本
    "target": "es5",
    // 允许从没有设置默认导出的模块中默认导入
    "allowSyntheticDefaultImports": true,
    // 将每个文件作为单独的模块
    "isolatedModules": false,
    // 启用装饰器
    "experimentalDecorators": true,
    // 启用设计类型元数据(用于反射)
    "emitDecoratorMetadata": true,
    // 在表达式和声明上有隐含的any类型时报错
    "noImplicitAny": false,
    // 不是函数的所有返回路径都有返回值时报错。
    "noImplicitReturns": true,
    // 从 tslib 导入外部帮助库: 比如__extends,__rest等
    "importHelpers": true,
    // 编译过程中打印文件名
    "listFiles": true,
    // 移除注释
    "removeComments": true,
    "suppressImplicitAnyIndexErrors": true,
    // 允许编译javascript文件
    "allowJs": true,
    // 解析非相对模块名的基准目录
    "baseUrl": "./",
    // 指定特殊模块的路径
    "paths": {
      "jquery": [
        "node_modules/jquery/dist/jquery"
      ]
    },
    // 编译过程中需要引入的库文件的列表
    "lib": [
      "dom",
      "es2015",
      "es2015.promise"
    ]
  }
}

tslint.json

Creating the tslint.json file in the root path is to introduce the standard specification of ts.

If the eslint configuration file has been introduced, this step does not need to be done.

{
  "extends": "tslint-config-standard",
  "globals": {
    "require": true
  }
}

Copy code

Attached is a default configuration of eslint automatically generated by the scaffolding eslintrc.js.

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    "plugin:vue/essential",
    "eslint:recommended",
    "@vue/typescript/recommended",
    "@vue/prettier",
    "@vue/prettier/@typescript-eslint"
  ],
  parserOptions: {
    ecmaVersion: 2020
  },
  rules: {
    "no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
    "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off"
  }
};

4. Support ES6/ES7

In tsconfig.json, add support for es6/es7. For more configuration, please see tsconfig - Compilation Options.

"lib": [
    "dom",
    "es5",
    "es6",
    "es7",
    "es2015.promise"
]

5. Configure Vuex

The first step is to install the dependencies first.

yarn add vuex vuex-class

Copy code

vuex: Centrally manage application status in vue

vuex-class: In vue-class- Bind vuex in component writing.

After quoting vuex-class, it is still a little different from the original writing method.

How to write in vuex store, how to write it, the reference is as follows:

import { Component, Prop, Vue } from "vue-property-decorator";
import { State, Getter, Action, Mutation, namespace } from "vuex-class";
// 声明使用的是哪个模块
const commonModule = namespace("common");
@Component
export default class HelloWorld extends Vue {
  @Prop() private msg!: string;
  // 获取vuex中的数据
  @commonModule.State("token") token!: string;
  @commonModule.Getter("getToken") getToken!: string;
  @commonModule.Action("setToken") actionSetToken: (arg0: string) => void;
  @commonModule.Mutation("setToken") mutationSetToken: unknown;
  // @State token
  // @Getter("token") getterToken;
  // @Action("token") actionToken;
  // @Mutation("token") mutationToken;
  created() {
    this.actionSetToken("123");
    alert(this.token);
  }
}

6. Support vue mixin function

Create a new mixins directory under src, according to the business Reuse module division structure.

We often use mixins when developing with Vue. After combining with TypeScript, there are generally two methods of mixins.

One is provided by vue-property-decorator

// 定义 routerMixins.ts文件
// mixin router 公共方法
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class myMixins extends Vue {
  /**
   * @author: WangXinYu
   * @describe: 浏览器后退事件
   * @param: {}
   * @return:
   **/
  goBack() {
    this.$router.go(-1)
  }
  /**
   * @author: WangXinYu
   * @describe: test
   * @param: {}
   * @return:
   **/
  routerTest() {
    console.log('are you ok?')
  }
}
// 引入 mixin
import { Component, Prop, Vue, Mixins } from 'vue-property-decorator'
import routerMixins from '@/mixins/router'
@Component
export default class HelloWorld extends Mixins(routerMixins) {
  created() {
    this.routerTest()
  }
}

The second one is mixed in @Component.

// mixins.ts
import { Vue, Component } from 'vue-property-decorator';
declare module 'vue/types/vue' {
    interface Vue {
        value: string;
    }
}
@Component
export default class myMixins extends Vue {
    value: string = 'Hello'
}
// 混入
import { Vue, Component, Prop } from 'vue-property-decorator';
import myMixins from '@/mixins/myMixins';
@Component({
    mixins: [myMixins]
})
export default class myComponent extends Vue{
    created(){
        console.log(this.value) // => Hello
    }
}

Are you all going to do it? If you don't understand, remember me. I am a senior front-end architect who debuted in 2008. If you have any questions or exchange experiences, you can enter my button skirt 519293536. I will try my best to help everyone.

The text and pictures of this article come from the Internet and add my own ideas. It is only for learning and communication, and does not have any commercial purpose. The copyright belongs to the original author. If you have any questions, please contact us in time for processing

(To be continued...)

The above is the detailed content of Practical combat with Vue+TypeScript project configuration. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Browser event loopNext article:Browser event loop