Create a project

// Create project command
# npm 6.x
npm init @vitejs/app my-vue-app --template vue

# npm 7+, an additional double horizontal line is required: NPM init@vitejs /app my-vue-app -- --template vue # yarn yarn create @vitejs/app my-vue-app --template vueCopy the code

Tips: An error will be reported when using YARN, I don’t know why, please inform the big guy if he knows

After the project is created

cd my-project

npm install
npm run dev
Copy the code

The introduction of the routing

npm i vue-router@4.09.
Copy the code

Create a router folder and create the index.ts file in the folder. The file content is as follows

import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";

const routes: Array<RouteRecordRaw> = [
    {
        path: "/".name: "index".component: () = > import(".. /pages/index.vue"),
        children: [{path: "/demoTable".name: "demoTable".component: () = > import(".. /pages/demo-table/list.vue")}]}]const router = createRouter({
    history: createWebHashHistory(),
    routes,
})

export default router;
Copy the code

Make the changes in the main.ts file

import { createApp } from 'vue'
import App from './App.vue'
import router from "./router"

createApp(App)
    .use(router)
    .mount('#app')

Copy the code

Reference eslint

1. Introduce ESLint and related plug-ins
npm i typescript eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin -D
Copy the code
  • Eslint: Core code for ESLint
  • @typescript-eslint/parser: EsLint’s parser that parses typescript to check and standardize typescript code
  • @typescript-eslint/eslint-plugin: The esLint plugin contains various types of defined specifications for detecting TS code
2. Introduce the Prettier
npm i prettier eslint-config-prettier eslint-plugin-prettier -D
Copy the code
  • Prettier: Core code of prettier
  • Eslint-config-prettier: resolves a conflict between the style specification of “esLint” and the style specification of “prettier”. The style specification of “prettier” prevails and becomes invalid automatically when “ESLint” is used
  • Eslint-plugin-prettier: uses prettier as an ESLint specification

. Eslintrc. Js configuration

module.exports = {
  // This is used to tell ESLint that the current configuration file cannot be found at the parent level
  root: true.// Global environment
  env: {
      node: true,},// Specify how to parse the syntax. The value can be null, but if it is not null, only this value can be configured
  parser: 'vue-eslint-parser'.// The parse configuration has a lower priority than parse
  parserOptions: {
    // Specify ESlint's parser
    parser: '@typescript-eslint/parser'.// The ES syntax is allowed
    ecmaVersion: 2020.// Import is allowed
    sourceType: 'module'.// Allow parsing JSX
    ecmaFeatures: {
      jsx: true,}},extends: [
    'plugin:vue/vue3-essential'.'plugin:@typescript-eslint/recommended'.'prettier',].rules: {
    'vue/no-multiple-template-root': 'off'.'array-bracket-spacing': ['error'.'never'].// Whether to allow extra Spaces in non-empty arrays
    'arrow-parens': 'off'.// The arrow function is enclosed in parentheses
    'block-spacing': ['error'.'always'].// => before/after parentheses
    'accessor-pairs': 'off'.// Use getters/setters in objects
    'block-scoped-var': 'off'.// Use var in block statements
    'brace-style': ['warn'.'1tabs'].// Brace style
    'callback-return': 'warn'.// Avoid calling the callback multiple times
    'camelcase': 'error'.// Mandatory hump naming
    'comma-dangle': ['error'.'never'].// Object literals cannot have commas at the end
    'comma-spacing': 'off'.// Spaces before and after commas
    'comma-style': ['error'.'last'].// Start or end of a line
    'complexity': ['off'.11].// Loop complexity
    'computed-property-spacing': ['off'.'never'].// Is it allowed to calculate the key name
    'consistent-return': 'off'.// Whether to allow omission after return
    'consistent-this': ['error'.'that']./ / this alias
    'constructor-super': 'off'.// Non-derived classes cannot call super; derived classes must call super
    'curly': ['error'.'all'].// Must use {} in if(){}
    'default-case': 'error'.// The switch statement must end with default
    'dot-location': 'off'.// The position of the object accessor, which is at the beginning or end of the line
    'dot-notation': ['off', { 'allowKeywords': true}].// Avoid unnecessary square brackets
    'eol-last': 'off'.// The file ends with a single newline
    'eqeqeq': 'error'.// Use === and! = =
    'func-names': 'off'.// Function expressions must have names
    'func-style': ['off'.'declaration'].// Function style, which states that only function declarations/function expressions can be used
    'generator-star-spacing': 'off'.// Whitespace before and after the generator function *
    'guard-for-in': 'off'.// The for in loop is filtered with the if statement
    'handle-callback-err': 'off'.// Nodejs processing error
    'id-length': 'off'.// The length of the variable name
    'indent': ['error'.4].// Indent style
    'init-declarations': 'off'.// An initial value must be assigned
    'key-spacing': ['off', { 'beforeColon': false.'afterColon': true}].// Spaces before and after colons in object literals
    'lines-around-comment': 'off'.// Note before/after a line
    'max-depth': ['off'.4].// Nested block depth
    'max-len': ['off'.80.4].// Maximum length of a string
    'max-nested-callbacks': ['off'.'error'].// Callback nesting depth
    'max-params': ['off'.3].// A function can take a maximum of three arguments
    'max-statements': ['off'.10].// There are at most several declarations in a function
    'new-cap': 'error'.// The first uppercase line of the function name must be called with new mode, and the first lowercase line must be called without new mode
    'new-parens': 'error'.// New must be in parentheses
    'newline-after-var': 'error'.// Whether an empty line is required after a variable declaration
    'no-alert': 'off'.// Disable alert Confirm prompt
    'no-array-constructor': 'error'.// Disallow array constructors
    'no-bitwise': 'off'.// Disable bitwise operators
    'no-caller': 'warn'.// Disable arguments.caller or arguments.callee
    'no-catch-shadow': 'error'.// Disallow catch clause arguments with the same name as external scope variables
    'no-class-assign': 'error'.// Disallow assigning values to classes
    'no-cond-assign': 'error'.// Disallow assignment statements in conditional expressions
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off'.// Whether to use console
    'no-const-assign': 'error'.// Disallow changes to const variables
    'no-constant-condition': 'error'.// Disable constant expressions in conditions if(true) if('warn')
    'no-continue': 'off'.// Disallow the use of continue
    'no-control-regex': 'error'.// Disallow the use of control characters in regular expressions
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'.// Whether to use debugger
    'no-delete-var': 'error'.// You cannot use the delete operator on variables declared by var
    'no-div-regex': 'warn'.// Can't use regular expression /=foo/ that looks like a division
    'no-dupe-keys': 'error'.{a:'warn',a:'warn'}
    'no-dupe-args': 'error'.// Function arguments must not be repeated
    'no-duplicate-case': 'error'.// The case labels in the switch must be unique
    'no-else-return': 'error'.// If an if statement contains a return, it cannot be followed by an else statement
    'no-empty': 'error'.// The contents of a block statement cannot be empty
    'no-empty-character-class': 'error'.// The [] content in the regular expression cannot be empty
    'no-empty-label': 'error'.// Disable the use of empty labels
    'no-eq-null': 'error'.// Disallow the use of == or! For null = operator.
    'no-eval': 'warn'.// Disable eval
    'no-ex-assign': 'error'.// Disallow assignment to exception arguments in catch statements
    'no-extend-native': 'error'.// Disable extension of native objects
    'no-extra-bind': 'error'.// Disallow unnecessary function binding
    'no-extra-boolean-cast': 'error'.// Disallow unnecessary bool conversions
    'no-extra-parens': 'error'.// Disallow unnecessary parentheses
    'no-extra-semi': 'error'.// Prohibit redundant colons
    'no-fallthrough': 'warn'.// Disable switch penetration
    'no-floating-decimal': 'error'.// Disallow omitting 'off' in floating-point numbers.5 3.
    'no-func-assign': 'error'.// Disallow duplicate function declarations
    'no-implicit-coercion': 'warn'.// Disable implicit conversions
    'no-implied-eval': 'error'.// Disallow implicit eval
    'no-inline-comments': 'off'.// Do not make remarks within the line
    'no-inner-declarations': ['error'.'functions'].// Disallow declarations (variables or functions) in block statements
    'no-invalid-regexp': 'error'.// Disallow invalid regular expressions
    'no-invalid-this': 'error'.// Disallow invalid this, only in constructors, classes, and object literals
    'no-irregular-whitespace': 'error'.// No irregular Spaces
    'no-iterator': 'error'.// Disallow __iterator__ attribute
    'no-label-var': 'error'.// The label name cannot be the same as the variable name declared by var
    'no-labels': 'error'.// Disable label declaration
    'no-lone-blocks': 'error'.// Disallow unnecessary nested blocks
    'no-lonely-if': 'error'.// Disallow the else statement to contain only if statements
    'no-loop-func': 'warn'.// Disallow the use of functions in loops (if there is no reference to an external variable and no closure is formed)
    'no-mixed-requires': ['off'.false].// Declaration types cannot be mixed
    'no-mixed-spaces-and-tabs': ['error'.false].// Prohibit the mixing of tabs and Spaces
    'linebreak-style': ['off'.'windows'].// Newline style
    'no-multi-spaces': 'warn'.// Do not use extra Spaces
    'no-multi-str': 'error'.// Strings cannot be wrapped with \
    'no-multiple-empty-lines': ['warn', {'max': 'error'}].// Blank lines cannot exceed a maximum of 'error' lines
    'no-native-reassign': 'error'.// Cannot override native objects
    'no-negated-in-lhs': 'error'.// The in operator cannot be left!
    'no-nested-ternary': 'off'.// Disallow nested ternary operations
    'no-new': 'warn'.// Disallow an instance constructed with new without assigning a value
    'no-new-func': 'warn'.// Disable new Function
    'no-new-object': 'error'.// Disallow new Object()
    'no-new-require': 'error'.// Prohibit using new require
    'no-new-wrappers': 'error'.// Do not use new to create a wrapper instance, new String new Boolean new Number
    'no-obj-calls': 'error'.// Cannot call built-in global objects such as Math() JSON()
    'no-octal': 'error'.// Forbade octal digits
    'no-octal-escape': 'error'.// Disallow octal escape sequences
    'no-param-reassign': 'error'.// Disallow reassigning parameters
    'no-path-concat': 'off'.// Node cannot use __dirname or __filename to concatenate paths
    'no-plusplus': 'off'.// Do not use ++, --
    'no-process-env': 'off'.// Disable process.env
    'no-process-exit': 'off'.// Disable process.exit()
    'no-proto': 'error'.// Disallow the __proto__ attribute
    'no-redeclare': 'error'.// Disallow repeated declarations of variables
    'no-regex-spaces': 'error'.// Disallow multiple Spaces in regular expression literals /foo bar/
    'no-restricted-modules': 'off'.// If the specified module is disabled, an error will be reported
    'no-return-assign': 'warn'.// The return statement cannot have assignment expressions
    'no-script-url': 'off'.// Disallow javascript:void('off')
    'no-self-compare': 'error'.// Can't compare itself
    'no-sequences': 'off'.// Disable the comma operator
    'no-shadow': 'error'.// A variable in an outer scope cannot have the same name as a variable or parameter in the scope it contains
    'no-shadow-restricted-names': 'error'.// Restricted identifiers specified in strict schema cannot be used as variable names at declaration time
    'no-spaced-func': 'error'.// There must be no space between the function name and () when the function is called
    'no-sparse-arrays': 'error'.// Disable sparse arrays, ['warn',,'error']
    'no-sync': 'off'.// Nodejs disables synchronizing methods
    'no-ternary': 'off'.// Prohibit the use of ternary operators
    'no-trailing-spaces': 'warn'.// No space after the end of a line
    'no-this-before-super': 'off'.// You cannot use this or super before calling super()
    'no-throw-literal': 'error'.// Disallow throwing literal errors: throw 'error';
    'no-undef': 'warn'.// There can be no undefined variables
    'no-undef-init': 'error'.// The variable cannot be initialized with undefined directly
    'no-undefined': 'error'.// 不能使用undefined
    'no-unexpected-multiline': 'error'.// Avoid multi-line expressions
    'no-underscore-dangle': 'warn'.// Identifiers cannot start or end with _
    'no-unneeded-ternary': 'error'.Var isYes = answer === 'warn'? true : false;
    'no-unreachable': 'error'.// Cannot have unexecutable code
    'no-unused-expressions': 'error'.// Disallow useless expressions
    'no-unused-vars': ['error', {'vars': 'all'.'args': 'after-used'}].// A variable or parameter that has not been used after it cannot be recorded
    'no-use-before-define': 'error'.// Cannot be used before it is defined
    'no-useless-call': 'error'.// Prohibit unnecessary calls and apply
    'no-void': 'error'.// Disable the void operator
    'no-var': 'off'.// Disable var and replace it with let and const
    'no-warning-comments': ['warn', { 'terms': ['todo'.'fixme'.'xxx'].'location': 'start'}].// There can be no warning remarks
    'no-with': 'error'./ / disable the with
    'object-curly-spacing': ['off'.'never'].// Whether to allow unnecessary Spaces within braces
    'object-shorthand': 'off'.// Enforces object literals to abbreviate syntax
    'one-var': 'warn'.// Continuous declaration
    'operator-assignment': ['off'.'always'].// Assignment operator += -= what
    'operator-linebreak': ['error'.'after'].// Operator at the end of the line is still at the beginning of the line
    'padded-blocks': 'off'.// Whether to make a blank line at the beginning and end of a block statement
    'prefer-const': 'off'./ / the preferred const
    'prefer-spread': 'off'.// Expansion is preferred
    'prefer-reflect': 'off'.// Reflect is preferred
    'quotes': ['warn'.'single'].// The quotation mark type is '' ''
    'quote-props': ['error'.'always'].// Whether to enforce double quotes for attribute names in object literals
    'radix': 'error'.// parseInt must specify the second argument
    'id-match': 'off'.// Named detection
    'require-yield': 'off'.// Generator functions must have a yield
    'semi': ['error'.'always'].// The statement enforces the semicolon ending
    'semi-spacing': ['off', {'before': false.'after': true}].// Space before and after the semicolon
    'sort-vars': 'off'.// Sort variables when declaring them
    'space-after-keywords': ['off'.'always'].// Whether to leave one space after the keyword
    'space-before-blocks': ['off'.'always'].// Block {that does not start with a new line should be preceded by a space
    'space-before-function-paren': ['off'.'always'].// Do you want a space before parentheses when defining a function
    'space-in-parens': ['off'.'never'].// Should there be Spaces inside the braces
    'space-infix-ops': 'off'.// Should there be Spaces around the infix operator
    'space-return-throw-case': 'error'.// Return whether to add a space after the throw case
    'space-unary-ops': ['off', { 'words': true.'nonwords': false}].// Do you want to add Spaces before/after unary operators
    'spaced-comment': 'off'.// Should the comment style include Spaces
    'strict': 'error'.// Use strict mode
    'use-isnan': 'error'.// Disable the use of NaN when comparing, only isNaN() can be used
    'valid-jsdoc': 'off'./ / jsdoc rules
    'valid-typeof': 'error'.// A valid typeof value must be used
    'vars-on-top': 'error'.Var must be placed at the top of the scope
    'vue/require-v-for-key': 'off'.// Whether vue's for loop must have a key
    'wrap-iife': ['error'.'inside'].// Execute the parenthesis style of the function expression immediately
    'wrap-regex': 'off'.// The regular expression literals are enclosed in parentheses
    'yoda': ['error'.'never'] // Prohibit yoda conditions}};Copy the code
NPM instruction
"script": {
    "lint": "vue-cli-service lint"
}
Copy the code

Format the project once when you run it and again before you package it. Save the last code is formatted

. Prettierrc configuration

{
  "printWidth": 80.// Output the (maximum) length of a single line (unfolded line)
  "useTabs": false.// Use Spaces instead of indents
  "tabWidth": 2.// The number of Spaces per indent
  "tabs": false.// Use TAB indentation instead of space
  "semi": true.// Whether to print a semicolon at the end of the statement
  "singleQuote": true.// Whether to use single quotes
  // "quoteProps": "as-needed", // Add quotes around object attributes whenever needed
  "quoteProps": "consistent"."trailingComma": "all".// Remove the comma following the last element of the object
  "arrowParens": "always".Arrow functions that take only one argument also need parentheses
  "rangeStart": 0.// The scope of each file format is the entire contents of the file
  "proseWrap": "always".// Fold the line when print width is exceeded
  "endOfLine": "lf".// Use lf for the newline character
  "bracketSpacing": true.// Whether to add Spaces to object properties
  "jsxBracketSameLine": true.// Place the > multi-line JSX element at the end of the last line, rather than the next line alone (not applicable to self-closed elements). The default is false, and select > not to start another line
  "htmlWhitespaceSensitivity": "ignore".// Specify the global whitespace sensitivity of HTML files. "ignore" - whitespace is considered insensitive
  "jsxSingleQuote": false.// JSX uses double quotes instead of single quotes
  "rangeStart": 0.// The scope of each file format is the entire contents of the file
}
Copy the code

The introduction of TS

npm install typescript
Copy the code

Configure the tsconfig.json file

{
    "compilerOptions": {
        // Allow a default import from a module that has no default export set. This does not affect the output of the code, just for type checking.
        "allowSyntheticDefaultImports": true.// Import helper functions from tSLIb (e.g. __extends, __rest, etc.)
        "importHelpers": true."target": "esnext".// Specifies which module system code to generate
        "module": "esnext".// Decide what to do with the module
        "moduleResolution": "node".// Specify the ECMAScript target version
        "strict": true."jsx": "preserve".// Generate the corresponding.map file.
        "sourceMap": true.// Ignore all type checking for declaration files (*.d.ts).
        "skipLibCheck": true."resolveJsonModule": true."esModuleInterop": true.// A list of libraries that need to be imported during compilation.
        "lib": ["esnext"."dom"].// Resolve the base directory for non-relative module names
        "baseUrl": ".".// List of module names to baseUrl based path mappings.
        "paths": {
            "@ / *": ["src/*"]."# / *": ["types/*"]},// A list of type declaration filenames to include
        "types": [
            // "node",
            "vite/client"]."typeRoots": ["./node_modules/@types/"."./types"]},"include": ["src/**/*.ts"."src/**/*.d.ts"."src/**/*.tsx"."src/**/*.vue"]}Copy the code

Change main.js to main.ts

Introducing Element (Vite)

npm install vite-plugin-style-import -D
Copy the code

Modify the configuration based on the official website

The problem record

The module solution for app.vue is not found where import App from ‘./ app.vue ‘is displayed: 1. Split the shims-vue.d.ts file in two

In the same directory as the shims-vue.d.ts file, create a new vue.d.ts file (not necessarily named vue, such as xxx.d.ts), and the file contains the following code

// vue.d.ts
declare module '*.vue' {
  import Vue from 'vue'
  export default Vue
}
Copy the code
// shims-vue.d.ts
import Vue from 'vue'
import VueRouter, { Route } from 'vue-router'
import { Store } from 'vuex'

declare module 'vue/types/vue' {
  interface Vue {
    $router: VueRouter;
    $route: Route;
    $store: Store<any>;
    // Here are the variables mounted to vue.prototype in main.ts$api: any; $mock: any; $configs: any; }}Copy the code

Reference:

Blog.csdn.net/fu983531588… Juejin. Cn/post / 684490…