How to build a TS-based basic scaffolding method with Vue-Cli3 scaffolding

Busy sneaked, sorted about how to build a Scaffolding of TS + decorator with Vue-CLI3, and how to customize WebPack configuration, optimize.

Preparation

@Vue / CLI @ 4.1.1

    Vue 2.6
  • Node V12 . 13.0
  • Mount Node

Installing Node mirror source management tool for NRM and NPM globally.

  • NPM I nrm -g // Install NRM LS // View Available Sources, and the current source, with * is currently used source NRM USE TAOBAO / / Switching source, using source NRM add
  • // where REIGSTRY is the source name, URL source path NRM DEL
// Deletes the response speed of the corresponding source NRM Test NPM // test source
   Install Vue-Cli3    
Reference official document: https: //cli.vuejs.org/en/guide/

NPM I @ Vue / CLI -G // Global Install Vue –Version // Checks if


Supplement

 NPM List -g - Depth 0 // View global installed package npm outdated -g --depth = 0 / / View Need to updateThe full-time package NPM Update package name -g // update global installed package   
Construction item

can be referenced: Use Vue-CLI 3.0 to build a Vue project
   

Vue Create Vue-CLI3 -TS
Remarks: If it is a Window system, use the git bash interaction prompt (switching) to work, use the following command to resolve:

WinPty Vue.cmd Create Vue-Cli3-TS

Custom Options – Manually Select Features
Add TS Support – TypeScript
  Based class-based components - Y  
Tslint
Add Router, Vuex, CSS (LESS or SCSS) pre-regulator, unit test (Jest)

 Up and down arrow keys   Space button Select 
Enter
  • Vue add @ Vue / TypeScript
  • All .js will be changed to .TS

script command [1

  • // – Start service NPM Run Serve // ​​- Package Compile NPM Run Build // – Execute the LintnPM Run Lint // – Execute Unit Test NPM Run Test: Unit
  • NPM Run Serve Startup Service: http: // localhost: 8080 / # /
VUE TS syntax


  Import {Component, Prop, Vue} from 'Vue-Property-Decorator' @ComponEnTexport DEFAULT Class HelloWorld Extends Vue {@Prop () Private Msg !: String;}  
The normal Vue project is different .VUE file Script of Script.

Vue-property-decorator

Usage can be referred to:

NPM
 Vue-Property-Decorator usage   

1. Type annotations, type inference

After the variable is notified by colon + type .

Compile time type check, write code time code reminder.

Type Inference, inference according to the type of assignment, the type limit is performed.
  Let Title: String; // Type Note Title = 'TS'; // Correct Title = 4; // Error Let Text = 'TXT'; // Type Inference Text = 2; // Error   When the VSCode editor is a red wavy prompt.  

Let Names: String []; // array

names = [‘Tom’];

  • let foo: any; foo = ‘foo’; foo = 3; let list: any [] (List = [1, True, ‘Free’]; List [1] = 100;

    Function Greeting: String {Return ‘Hello,’ + Person;} // Void type, often used for functions without return values ​​Function Warnuser (): void {Alert (‘this is msg’)
  • Case: Vue Demo
   

Import {Component, Prop, Vue} from ‘Vue-Property-Decorator’; @ ComponENTEXPORT Default Class Demo Extends Vue {// is equivalent to data items in Data features: string []; constructor () {super (); this.features = [‘Type Note’, ‘Type Inspiration’, ‘Compilation Language’];} // Methods of Methods ADDFETURE (event: any) {console.log (event); this.Features.push (event.target.value); event.target.value = ‘;}}

2. Class
   The class and ES6 in the TS are substantially the same, and the property access modifiers  
Private property, cannot access

Protected protection attribute outside the class, can access internal and derived classes in the class, can not be accessed outside the class

public Public attributes can be accessed anywhere, the default value
 Readonly read-only properties must be initialized in the declaration or constructor, and cannot change the value   
constructor: initialization member variable , Parameter plus modifiers, can define and initialize an attribute

Constructor (PRivate name = ‘TOM’) {super ();}
   

Name: String; Constructor () {super (); this.name = ‘Tom’;}

Accessor, additional logic can be added when exposing access data; available in VUE Calculation attribute
   Get fullName () {return this.name;} set fullname (val) {this.name = val;} 
Number of features: {{count}}
Export DEFAULT CLASS DEMO EXTENDS VUE {// Defines Getter as a calculation attribute Get () {return this.features.length;}}


interface

    Only the interface is only constrained, and

Interface: lastname: string;} function Greeting (Person) : Person) {Return `Hello, $ {Person.firstname} $ {Person.Lastname} `;} const user = {firstname: ‘jane’, lastname: ‘user’}; console.log (Greeting (user));
   Case: VUE Demo, declare interface type constraint data structure 

{{feature.name}}

// Define an interface Structural architecture interface feature {id: Number; name: string;} vue {private class demo extends vue {private features: feature []; constructor () {super (); this.features = [{ID: 1, Name : ‘Type Note’}, {ID: 2, Name: ‘Type Inference’}, {ID: 3, Name: ‘Compilation Language’}]}
   

The genericity means that the specific class does not specify the specific class in advance when defining functions, interfaces, or classes, but specifies the type when used. A feature.
  Interface Result  {DATA: T;} // Does not use generic interface results {data: feature [];} 

Case: Use generic constraint interface return type
  Function getData 

(): Result

{const data: any = [{id: 1, name: 'Type Note'}, {ID: 2, Name: 'Type Inference'}, {ID : 3, Name: 'Compilation Language'}]; return {data};} // call this.features = getData (). Data;
Case: Use generic constraints to return to type Promise


Function Getdata

(): promise

> {const data: any = [{id: 1, Name: ‘Type Note’}, {ID: 2, Name: ‘Type Inference’}, {ID: 3, Name: ‘Compilation Language’}]; Return Promise.Resolve

> ({DATA}); } // Call async mode async mounted () {this.features = (AWAIT GETDATA
()). Data;} // Call the THEN Mode MOUTED () {getData (). THEN (((res)
) => {this.features = res.}   
Decorator

Decorator is used to expand class or its properties and methods.
 Attribute statement: @Prop   
  • In addition to declaring in @component, @prOP mode Declaration Component Attribute
  • Export Default Class Demo Extends Vue {// PROPS () parameter provides Vue to provide attribute options //!, it is called clear assignment, it Is provided to TS @Prop ({type: string, request: true}) private msg !: string;}
    Event processing: @emit

    // Notify the parent class new event, if the function name is not specified as an event name (hump variably separated) @Emit () Private AddFeature (Event: any) {// If there is no return value, it will be used as an event parameter const feature = {name: event.target.Value, ID: this.features.Length + 1}; this.features.push (feature); Event.target.Value = “”; return value; // Return value as an event parameter}

    Template Template Component Written Normally, @ add- Feature
    Change monitoring: @watch
       @watch ('msg') OnRouteChange (Val: string, oldval: any) {Console.Log (Val, OldVal);}  
    Decorator Principle

    The decorator is essentiallyFactory function, modify the incoming class, method, attribute, etc.
        // class decorator expression is treated when running The function is called, the constructor of the class is the only parameter thereof. Function log (target: function) {// target is constructor console.log (target === foo); // true target.prototype.log = function () {console.log (this.bar);} // If the class decorator returns a value, it uses the supplied constructor to replace the category declaration. } @logclass foo {bar = 'bar'} const foo = new foo (); @ @ Ts-ignorefoo.log ();   combat Component, new construction Decor.Vue 
    {{msg}}

    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 {}
       SourceThe code is simple to understand <Result <Result   The class decorator is mainly dependent on the library: Vue-Class-Component, in-depth source, what is it did behind?  Vue-Property-Decorator.js  
    Import Vue from ‘Vue’; Import Component, {CreateDecorator, Mixins} from ‘Vue-Class-Component ‘; Mixins as mixins};

    CreateDecorator, Applymetadata is the core, follow-up implementation relies on it, such as Prop, Watch, Ref.

    Export Function Prop (Options) {if (Options === Void 0) {Options = {};} Return Function (Target, Key) {Applymetadata (Options, Target, Key); CreateDecorator (Function (ComponentOptions, K) {; (ComponentOptions.props |) [K] = Options;} (Target) (Target) [K] = Options;} (Target) (Target) (Target) (ComponentOptions.props |) [K] = Options;}) [K] = Options;} (Target) (Target) (Target) (COMPONENTOTIONS.PROPS =}) [k] = options;}) , Key);};}

    Applymetadata, see the name of the name, is to put out the information in the decorator in 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 Gets metadata set on the class decorator. Refer to article understanding:  
    DecoScript: Understand Reflect Metadata
    JavaScript Reflect Metadata Detailed

    CreateDecorator, see Nomadical Righteousness is to create an decorator. Essentially is defined in the class

      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 (options) {Return Factory (Options, Key, Index);};};}  

    In the project root directory, new Vue.config.js
    local development API agent
       
    Module.Exports = {DevServer: {proxy: {‘/ api’: {target: ‘, changeorigin: true, Pathrewrite: {‘ ^ / API ‘:’ ‘}}}}}

    Local development API simulation

    DevServer : {Before (app) {before (app) {app.get (‘/ API / getList’, (REQ, RES) => {rEs.json ({DATA: [{ID: 1, Name: ‘Vue’}]}})}}}

      Performance Optimization  

    Add command in package.json file Script:
      "Build: Report": " Vue-cli-service build --Report " 
    will generate Report.html in the dist catalog, can be opened directly, check the package dependence, analyze, and optimize
    Package optimization - CDN introduced into public library Add configuration in vue.config.js:

    ConfigureWebPack: {EXTERNALS: {/ / cdn outer chain, avoid Bao Tai, the first screen optimization ‘Vue’: ‘Vue’, ‘Vue-router’: ‘Vuex’, ‘Vuex’: ‘Vuex’}}

       

     Optimization, HTML HEAD information, DNS domain predetermined, JS library reload preload.   

      Other  
    Modify the local development port number, add configuration in Vue.config.js:

      DEVSERVER: {Port: 8888}
    • Experience optimization – packaging completion tips:
    Const WebpackBuildNotifierPlugin = Require ‘WebPack-Build-Notifier’; const path = request (‘path’); module.exports = {// chain operation chainwebpack: config => {// Remove PreFetCH plugin, mobile terminal to bandwidth sensitive // ​​route Lazy loading, only route to users frequently, get // component in advance by comment: () => import (/ * webpackchunkname: “about” * / / * WebPackPrefetch: True * / ‘.. / views / about.vue ‘) config.plugins.delete (‘ prefetch ‘); // Production package tips, development does not prompt IF (process.node_env ===’ product ‘) {config.plugin (‘ build-notify ‘). USE (WebPackBuildNotifierPlugin, [{Title: “My Project Webpack Build”, LOGO: path.resolve (“./ img / favicon.png”), Suppresssuccess: true}]}}}

    The above is all the content of this article, I hope that everyone’s learning is helpful, and I hope that you will support Tumi Clouds.
                        
    © Copyright Notice
    THE END
    Just support it if you like
    like0
    share
    comment Grab the couch

    Please log in to comment