There is an old saying that a project can be rewritten ten times in code, and each time you make a lot of money. SSR will continue to be reconstructed.

When using TS in vUE, there are two cases:

  1. In the vuE-CLI 3.0 old project.
  2. In the latest vuE-CLI 3.0.

Vue cli – 3.0

Using typescript in the latest VUE-CLI 3.0 is very convenient because of the added SUPPORT for TS. When using the Vue Create project, select the second custom configuration to add SUPPORT for TS, and don’t forget to add ts-Lint syntax checking. As for how to install VUE-CLI 3.0, go to the official documentation to know. If you want to make this the default configuration, the documentation also provides the following configuration so that you can click the first option and it will be automatically configured.

The saved preset file will be stored in a JSON file named.vuerc in the user’s home directory. Edit this file if you want to change preset/option that is saved.

During project creation, you will also be prompted to choose your preferred package manager or use the Taobao NPM image source to install dependencies faster. These selections will also be stored in ~/.vuerc.

Once the project is initialized, it’s ready to use out of the box. Json file, typescirpt and ts-loader are configured for you, and vue-class-component, The two plugins that add VUE support for TS are also installed, the latter is an extension of the former, and the tsconfig.json and.d.ts files are also configured. I’ll give you some examples, too. Of course, the examples are not enough. You can go to the Github repository for the two plug-ins and see the documentation. It is very simple to use, almost removing the black box of vue and adding a syntax modifier. Detailed configuration will be put in the following vuE-CLI 3.0 steps to write it, also need not be so cumbersome, after all, the following need to manually configure.

Vue – cli below 3.0

To initialize a vuE-CLI 2.0 project, the documentation also gives the corresponding method:

Vue CLI 3 uses the same Vue commands as the older version, so Vue CLI 2 (VUe-CLI) is overwritten. If you still need to use older versions of vue Init, you can install a bridge tool globally:

npm install -g @vue/cli-init
# 'vue init' will work the same as' [email protected] '
vue init webpack my-projectCopy the code

The dev command in script is based on webpack-dev-server. The dev command in script is based on webpack-dev server. Vue-cli 2.0 is made up of webpack plus vue-loader, so plug-ins need to be installed one by one and automatically configured in package.json. The next step is to install the various dependencies.

npm install typescript ts-loader --save-devCopy the code

After the installation, how to configure the tutorial, in the TS-Loader NPM package documentation and ts official documentation written in detail, the following I talk about my own reconstruction project used it!

To configure ts-loader into webpack, go to webpack.config.js and use vue-cli2.0 (build folder) to find webpack.base.conf.js:

resolve: {
   extensions: ['.js'.'.vue'.'.json'.'.ts'], // Add. Ts file parsing, if using TSX, add italias: {
      'vue$': 'vue/dist/vue.esm.js'.The '@': resolve('src'),}},Copy the code

Then add ts-loader:

 module: {
    rules: [
      ...(config.dev.useEslint ? [createLintingRule()] : []),
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: vueLoaderConfig
      },
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        options: {
          appendTsSuffixTo: [/\.vue$/],
        }
      },Copy the code

Due to the use of the grammar test, so also need to this configuration file, and then to the entrance to the file. Ts, to go under the SRC directory. The main js to main. Ts:

const createLintingRule = () => ({
  test: / \. (js | vue | | ts TSX) $/, / / configured ts, TSX grammar testing support loader:'eslint-loader',
  enforce: 'pre',
  include: [resolve('src'), resolve('test')],
  options: {
    formatter: require('eslint-friendly-formatter'), emitWarning: ! config.dev.showEslintErrorsInOverlay } })Copy the code

entry: {
   app: './src/main.js'.ts},Copy the code

To get the project up and running again, check out the OFFICIAL TS documentation. Same as above for the next project.

TypeScript uses the tsconfig.json file to manage project configuration, so you need to include this file in the vue-CLI layer 1 file.

The configuration of the file is also explained very patiently in the ts official website project configuration. Now I will talk about what I have written.

// tsconfig.json {// The file to compile"include": [
      "src/**/*"], // The compiled files need to be ignored"exclude": [
      "node_modules"], // compiler"compilerOptions": {// Contains a list of types that declare file paths"typeRoots": [
        "node_modules/@types"], // Parse in strict mode"strict": true// Allow default imports from modules that do not have default exports set"allowSyntheticDefaultImports": true// Enable the decorator"experimentalDecorators": true// Disable bidirectional covariant checking for function arguments."strictFunctionTypes": false// Allows javascript files to be compiled"allowJs": true, // The adopted module system"module": "esnext", // Compile the output target ES version"target": "es5"// How to handle modules"moduleResolution": "node"// There is an error with an implied any type on expressions and declarations"noImplicitAny": true, // A list of library files that need to be imported during compilation."lib": [
        "dom"."es5"."es6"."es7"."es2015.promise"]."sourceMap": true, // Style errors and messages, using colors and context."pretty": true}}Copy the code

The compilerOptions option can be added to that list as needed, such as some code constant detection.

If your project uses NPM packages, third-party plug-ins, etc., create a declaration file for them in TS, such as if you are using Vue. Create a vue.vue-shims.d.ts.

declare module '*.vue' {
    import Vue from 'vue'
    export default Vue
}Copy the code

See the documentation for more details.

Install the vue-class-component and vue-property-decorator plugins mentioned above. The rules are specified in their Github repository, which is an extension of vue-class-component. Generally choose the latter can be.

Here basically can crazy masturbating TS code, is not feeling very exciting, or personally recommended to use vuE-CLI 3.0, not to mention the SUPPORT for TS, the whole project looks very clean.

Below I paste a few parts with TS written. Vue file as a reference! For details, please check github warehouse.

<template>
  <div class="hello">
    <form id="loginFrom" method="get" action="#" @submit.prevent>
      <div class="input" id="nkdiv">... <div id="login-btn">
        <my-button 
          :disabled="button.disabled" 
          :value="button.value" 
          :btnStyle="button.btnStyle" 
          @click.native="login"
        />
      </div>
      <router-link to="/reset"><span class="button"> Forget your password? </span></router-link> <router-link to="/register"><span class="button" id="register-btn"> Register new users </span></router-link> </form> </div> </template> <script lang='ts'>
import { Vue, Component } from "vue-property-decorator"; /** * Here is a plugin for vuex-class. It does not support the use of class classes to write vuex. It simply supports TS. * https://github.com/ktsn/vuex-class * so I made a simple packaging, let vuex have inherited property, but in its lot below I really big write vuex - class. Js, is the * support class way, You are welcome to check it out. https://github.com/lzxb/vuex-class.js * / / / here is a decorator, corresponding vuex inside that several map... Import {Action, Mutation, Getter, namespace} from'vuex-class';
import { Toast } from '.. /common/comjs'; // The login Module is connected. const loginModule = namespace('login'); @Component({ components: {// write the component you are referencing here}, /* Since vue-property-decorator does not allow new attributes to be added, the same attributes as data,methods, etc., are valid only in this decoratorexportClass this has this property, but does not get */})exportDefault class login extends Vue {// the default class login extends Vue {// the default class login extends Vue$isEmpty@loginmodule.mutation ('$isEmpty') $isEmpty: any;
    @loginModule.Getter('_isEmpty') isEmpty: any;
    @loginModule.Action('userLogin') userLogin: any;
    @loginModule.Mutation('$assignParams') $assignParams :any;
    @loginModule.Getter('_res') res: any;

    nickname: string = ' ';
    password: string = ' ';

    button: MyButton.Button<MyButton.BtnStyle> = {
        disabled: false,
        value: 'login',
        btnStyle: {
          width: '7.75 rem',
          height: '1.175 rem',
          fontSize: '0.5 rem'}}created () {
        if(! this.$route.query.nickname) return;
        this.nickname = this.$route.query.nickname
    }

    async login () {
        let params = {
            nickname: this.nickname,
            password: this.password
        }
        this.$isEmpty(params);
        if (this.isEmpty) return Toast(' '.'Username and password cannot be empty');
        this.$assignParams(params);
        this.button.disabled = true;
        await this.userLogin();
        setTimeout(() => {
            this.button.disabled = false;
        }, 1000);
        if (this.res.data.token) {
            ...
        } 
        Toast(' ', this.res.data); }}Copy the code

Github address based on VUE-Cli3.0

Github address based on VUE-Cli2.0 + SSR + PWA (using PWA offline cache technology, welcome start)

Personally feel that after ts, the code style is very cool, the code hints are complete, basically as long as the chain, as long as the way can be written, with JS often write wrong function names, variable names and so on, because the hint is very few. Can stick a code to come out to see, really thief cool. The following is the way to write the vuex class, especially recommend the Wolf boss vuex-class.js plug-in.

class View extends BaseLoaderData<ChatRoom.View.RequestParams, string> {
	readonly namespaced: boolean = true;
	public readonly state: ChatRoom.View.State = {
		params: {
			id: ' '
		},
		res: { code: 0, data: ' ' },
		requestStatus: 'unrequest'
	};
	async saveView(): Promise<this> {
		this.$RequestStart(a); const res = await this.api.saveView(this.state.params); this.$RequestSuccess(res);
		return this;
	}
}
class ChatRoom extends VuexClass {
	readonly namespaced: boolean = true;
	articList: ArticList;
	view: View;
	modules: {
		articList: ArticList;
		view: View;
	};
	constructor() { super(new chatroom()); this.articList = new ArticList(); this.view = new View(new chatroom()); this.modules = { articList: this.articList, view: this.view }; }}export default ChatRoom;Copy the code

Welcome to exchange, if you feel helpful, welcome to start.