What is TypeScript?

TypeScript is a superset of JavaScript; TypeScript has all of the same features that JavaScript does; TypeScript is ultimately parsed into JavaScript rendering; TypeScript makes up for JavaScript’s weakness in typing. JavaScript is known to be a weak language (with no mandatory typing requirements), so TypeScript was invented.

JavaScript is a prerequisite for front-end development, so we can just look at the TypeScript documentation and get started. Because even if you write the same JavaScript syntax in a TS file it will still work and be packaged and deployed; But! There will be a lot of red errors and yellow warnings in the editor or when packing. Can’t stand ~~~; It is not visible on the browser console (note: this is not recommended and should not be developed directly, I would like to express that it is more efficient not to shy away from the code).

We as a code monkey must be strict with ourselves not to be so casual; And avoid getting into habits; Or if a colleague sees your code, trust me, he will despise you. When developing TypeScript, we should always pay attention to compiler prompts to correct them; Personal purpose: do not let the project appear a red error and yellow warning, can be said to be obsessive-compulsive ~~!

A:

Install VUE-Cli3.0 and create the project! Uninstall vuE-CLI2 that you installed on your computer

NPM uninstall vue-cli -g // Uninstall cli2 NPM install -g@vue /cli // Install the new version vue create vue-cli3-project // Create the new versionCopy the code

2: Select Manually Select Features and press Enter According to the following figureThe blank space keyHit Enter

Three: install vue official plug-in details click

Vue-property-decorator gold digger blogger

npm i vue-class-component vue-property-decorator --save
Copy the code

4: Add the vue.config.js entry file to the root directory. The following contents can be modified according to your requirements

Const path = require('path') const resolve => {return path.join(__dirname, dir)} Const BASE_URL = process.env.node_env === 'production'? '/' : '/' module.exports = {baseUrl: BASE_URL, outputDir: 'dist', // Package generated production build files assetsDir: '/' : '/' module.exports = {baseUrl: BASE_URL, outputDir: 'dist', // package generated production build files ", // place the generated static resource path, default in outputDir indexPath: 'index.html', // specify the generated indexPath input path, default outputDir pages: RuntimeCompiler: true, productionSourceMap: false, // Start source map in production environment? chainWebpack: Config => {config.resolve.symlinks(true) // Fix Lazy loading routes Error:  Cyclic dependency [https://github.com/vuejs/vue-cli/issues/1669] config.plugin('html').tap(args => { Args [0].chunkssortMode = 'none' return args}) // Configure path alias config.resolve.alias.set ('@', resolve(' SRC ')).set('_c', Resolve (' SRC /components')) if (process.env.is_analyz) {config.plugin('webpack-report') .use(BundleAnalyzerPlugin, [{ analyzerMode: 'static', }]); }}, CSS: {modules: false, // enable CSS modules // extract: true, // use CSS sourceMap: false, // enable CSS source maps LoaderOptions: {} // CSS default configuration items}, devServer: {open: true, // automatically open browser port: 8089, // port proxy: "// set proxy}}Copy the code

5. Adding the tsconfig.json verification rule to the root directory is equivalent to Eslint

{ "defaultSeverity": "warning", "extends": [ "tslint:recommended" ], "linterOptions": { "exclude": ["node_modules/**"]}, "rules": {"quotemark": false, // String characters require single or double quotation marks. "Indent ": false, // use tabs or Spaces to enforce indentation. "Member-access ": false, // Requires an explicit visibility declaration for class members. "Interface-name ": false, // The interface name is required to start with uppercase "ordered-imports": false, // the import statements are required to be sorted alphabetically and grouped. "Object-literal-sort-keys ": false, // Check the sorting of keys in object literals. "No-avatar-blank -lines": false, // One or more consecutive blank lines is not allowed. "No-shadowed-variable ": false, // Hiding variable declarations is not allowed. "No-trailing -whitespace": false, // trailing Spaces are not allowed at the end of the line. "Semicolon ": false, // whether the trailing comma ends with "trailing comma": false, // whether the trailing comma ends with "eofline": False, // prefer-conditional-expression: false, // for (... in ...) Statements must be filtered with if statements "curly": true, //for if do while parentheses "forin": false, //for in must be filtered with "import-blacklist": "No-arg ": true, // argument is disallowed. Callee "no-bitwise": True, // Bitwise operator "no-console": false is not allowed, // console" no-construct": String/Number/Boolean constructor "no-debugger": true, // debugger" no-duplicate-super": // Empty block "no-eval": true, // Eval "no-floating-promises" is not allowed: False, // Promise return function "no-for-in-array": false, // for in count group "no-implicit-dependencies": False, // don't import the module "no-demonstrator-object-type" in the project package.json that is not listed as a dependency: False, // Type inference "no-invalid-template-strings": true using {} in functions and constructors is disallowed, // warning ${"no-invalid-this" in non-template characters: True, // Disallow the use of this keyword" no-misused-new": true, // disallow the definition of constructors or new class "no-null-keyword": False, // Forbid null keyword "no-object-literal-type-assertion": false, // Forbid object in type assertion expressions "no-return-await": True, // return await "arrow-parens": false, // Parameters defined by arrow functions require parentheses "anoplace-overload -signatures": False, // Enforces function overloads to be avg. "ban-comma-operator": true, // disallow the comma operator. "No-any ": false, // Do not use any type "no-empty-interface": true, // disable empty interface {} "no-internal-module": True, // Does not allow the internal module "no-magic-numbers": false, // does not allow constant values outside of variable assignments. When no list of allowed values is specified, the default is -1,0, and 1 "no-namespace": [true, "allPW-declarations "], // Internal modules and the "no-non-null-assertion" namespace are not allowed: True, // Not allowed! Nonnull assertions for postfix operators. "No-parameter -reassignment": true, // no reassignment of parameter "no-reference": True, // <reference path=> import, use import instead of "no-require-type-assertion ": False, // warning "no-var-requires" if the type assertion does not change the type of the expression: False, // var module = require("module") is not allowed, import foo = require('foo') import "prefer-for-of": true, // recommend for(.. Of) "promise-function-async": false, // Request asynchronous function return promise "max-classes-per-file": [true, 2], // The maximum number of declaration classes in a script "variable-name": false, "prefer-const": falseCopy the code

Six: start the project can see the initialization effect; At this point, the project is completed

npm run serve 
Copy the code

Vue page instance

<template> <! <div> <! --DOM--> </div> </template> import { Component, Emit, Inject, Model, Prop, Provide, Vue, Watch } from 'vue-property-decorator' @Component export default class Login extends Vue { @Prop() propA: number = 1 @Prop({ default: 'default value' }) propB: string @Prop([String, Boolean]) propC: string | boolean @Prop({ type: null }) propD: Any @watch ('child') // Private void private onChanged1(val: string, oldVal: string): Void {} // Pubilc onChanged2(val: string, oldVal: String) {return val}} <style scoped>Copy the code

The code above is equivalent to:

export default { props: { checked: Boolean, propA: Number, propB: { type: String, default: 'default value' }, propC: [String, Boolean], propD: { type: null } } methods: OnChanged1 (val, oldVal) {}, onChanged2(val, oldVal) {return val}, watch: {'child': {handler: onChanged1(val, oldVal) {}, onChanged2(val, oldVal) {return val}}, watch: {'child': {handler: 'onChildChanged', immediate: false, deep: false } } }Copy the code

Conclusion:

  • thinkTypeScriptWill be the future direction of development; So get started early!
  • When you useVue3.0 + TypeScriptUsed to developreact.jsAs you’ll find out,vue3.0More and more likereact.jsA; I don’t think this is what vue’s loyal fans want, but then again, we’ll just have to accept it…
  • Vue3.0 + TypeScriptcontrastvue2.0removeTypeScriptIntrinsic difference; The difference in the way you write it is a little bit more intuitive that in the old method the function would be placedmethodsCycle,Vue3.0 + TypeScriptIt can be said that it does not existmethodsThis life cycle, so it’s more and more likereactthe

End: The actual project will be uploaded to gitHub later. At present, it is a complete online project. It is impractical and impossible to upload all the projects. Welcome to correct any problems or errors;

The article part reference segmentfault.com/a/119000001…

Decorator juejin.cn/post/684490…