Vue - 12 Vue cli 3. X scaffold construction project

Keywords: Vue

Vue family bucket -- 12   Vue cli 3. X scaffold construction project

12.1 what is Vue cli

1. Vue cli is a tool officially provided by Vue to build a project scaffold. It is a standard tool developed by Vue.js. It has integrated webpack and built many common configurations, making it more standardized when using Vue to develop projects.
2. Function: download template items through Vue cli.
3. Official documents: https://cli.vuejs.org/zh/
4. github site: https://github.com/vuejs/vue-cli

 

12.2 Vue CLI installation

1. Install Vue CLI globally

npm install -g @vue/cli

2. After successful installation, you can use the vue command on the command line, such as viewing the currently installed version:

vue --version
# Or capital V
vue -V

 

12.3 creating projects based on Vue cli

Run the vue create command to create a new project

vue create entry name

 

12.3.1 create default project

**Create a new project, enter the folder, cmd create

vue create myvuecli-demo1

**Prompt to select Default or manual creation. Vue2 is created by default here

**cd myvuecli-demo1

** npm run serve

**Access: http://localhost:8080/

 

 

12.3.2 creating user defined items

 ** Create project   vue-cli-demo2 manual creation

vue create vue-cli-demo2

 

 

 ** As shown in the figure below, select the configuration options according to the project requirements (press the spacebar to select or cancel, and a to select all)

Bable, (commonly used) solves compatibility problems and supports the translation of ES6 code into code recognized by the browser
TypeScript is a language extension that adds features to JavaScript and adds many functions. It was developed by Microsoft
Progressive Web App (PWA) Support, progressive Web application support
Router, (commonly used) is Vue router routing.
Vuex is the state management mode + library (common) of Vue.js application.
CSS pre processors, (commonly used) support CSS preprocessor and Sass/Less preprocessor.
Linter / Formatter, (commonly used) supports code style checking and formatting.
Unit Testing supports Unit Testing.
E2E Testing supports E2E Testing.

 

**Select the corresponding option to proceed to the next step

 ** Select the corresponding version of vue.js

 ** Tip: whether to use the route in history mode, press enter

**Select CSS preprocessor and the first with dart sass

**Select ESLint + Prettier     Check and format code

 ** Select the syntax check method. Here, select Save to check

 ** You will be prompted: where to put the configuration of Babel, postcss and eslint, select: put it in a separate file, and then press enter

 ** You will be prompted: do you want to save the configuration of the current project settings as pre configuration so that you can continue to use this set of configuration when creating a project later?

Press enter to save. The next time you create a project, you will have one more option (vue-cli-demo2)

If you want to delete preset, delete it in the. vuerc file under C:\Users \ your user name directory

**Run

cd vue-cli-demo2
npm run serve

 

12.4 CLI service commands  

reference resources: https://cli.vuejs.org/zh/guide/cli-service.html

CLI service (@ Vue / cli service) is a development environment dependency. Optimized internal webpack configuration for most applications.
In a Vue CLI project, the @ Vue / cli service module installs a command called Vue CLI service.
Specify Vue cli service related commands in scripts in package.json.

"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  }

**serve starts a development environment server (based on webpack dev server)   (after modifying the component code, the hot module will be replaced automatically)

**build will automatically create a dist / directory under the root directory of the project, and the packaged files are in it

The packaged js will automatically generate files with suffixes of. js and. map

js file: it is compressed and encrypted. If an error is reported during operation, the output error information cannot be accurately located. The code reports an error

map file: the file is relatively large and the code is not encrypted. It can accurately output which line and column are wrong.

**lint uses Eslint to check and fix the specification of the code

For example, add more spaces to the format in main.js. After npm run lint is executed, it will automatically remove redundant spaces.

npm run serve
npm run build
npm run lint

 **vue-cli-service inspect

You can use Vue CLI service inspect to review the webpack config of a Vue CLI project.

 

12.5 scaffold project structure

|-- node_modules: Folder where download depends
|-- public: Storing static files that do not change src/assets The difference is, public The files in the directory are not webpack Packaging processing, will be the original
Sample copy to dist Directory
|-- index.html: Master page file
|-- favicon.ico: Icons displayed on the browser
|-- src: Source folder
|-- assets: Storing static resources in components
|-- components: Store some common components
|-- views: Store all routing components
|-- App.vue: Application root master
|-- main.js: Application entry js
|-- .browserslistrc: Specifies the target browser range that the project is compatible with, Corresponding to package.json of browserslist option
|-- .eslintrc.js: eslint Related configuration
|-- .gitignore: git Configuration ignored by versioning
|-- babel.config.js: babel Configuration of,Namely ES6 Syntax compilation configuration
|-- package-lock.json: It is used to record the specific source and version number of each package actually installed in the current state, Make sure others are there npm install term
 At present, everyone's dependence can ensure consistency.
|-- package.json: Basic information of the project,Package dependent configuration information, etc
|-- postcss.config.js: postcss A pair of css Compiled tools, similar to babel yes js Treatment of
|-- README.md: Project description readme file

The configuration of browsers is as follows:

Code    meaning
last 2 versions            The last 5 versions of each mainstream browser
last 2 Chrome versions    The last two versions of Google browser
> 2%            Market share greater than 2%
> 2% in US           US market share greater than 2%
ie browser 6-8
Firefox > 20 Firefox version > 20
Firefox < 20
since 2013             All versions released after 2013
IOS 7 specifies the IOS 7 browser

 

12.6 custom configuration

Create the vue.config.js file in the project root directory.
vue.config.js basic common configuration (see the document for other details: https://cli.vuejs.org/zh/config/#vue-config-js)

module.exports = {
    devServer: {
        port: 8001, // Port number. If the port is occupied, it will be automatically raised by 1
        open: true, // Start the service and open the browser automatically
        https: false, // agreement
        host: "localhost", // Host name, or 127.0.0.1 Or 0 during real machine test.0.0.0
    },
    lintOnSave: false, // default true, Warnings are only output to the command line and do not fail compilation.
    outputDir: "dist2", // The default is dist ,Directory where packaged files are stored,
    assetsDir: "assets", // Store generated static resources (js,css,img,fonts) of (be relative to outputDir) catalogue
    indexPath: "out/index.html", // default index.html, Specify generated index.html Output path for (be relative to outputDir). 
    productionSourceMap: false, // When packing, Do not generate .map file, Accelerate package build
};

 

 

12.7 Eslint plug-in

12.7.1 what is ESLint

ESLint is a grammar rule and code style checking tool, which can be used to ensure that the syntax is correct and the style is unified.
If we enable Eslint, it means that we have to accept its very harsh syntax checks, including no less or more spaces, no single quotation, no double quotation, no semicolon after a statement, etc. These rules can actually be set.

Vue cli is on / off by default, and vue.config.js is customized    lintOnSave: false/true to control

 

12.7.2 introduction to eslint configuration

In the package.json file under the project root directory, you can configure the eslintConfig option or. eslintrc.js

"eslintConfig": { // eslint to configure
  "root": true, // Used to tell eslint Cannot find current profile
  "env": { // Specify the environment you want to enable. The following configuration is specified as node environment
  "node": true
  },
  "extends": [
  "plugin:vue/essential", // Format code plug-in
  "eslint:recommended" // Enable recommendation rules
  ],
  "rules": { //Add custom rule
  "semi":[1,'never'], // Semicolons are prohibited
  "indent": [2, 2] // Indent with 2 spaces
  },
  "parserOptions": {
  "parser": "babel-eslint" //Used to specify eslint Parser
  }
  },

 

12.7.3 custom syntax rules

Reference: Vue Github documentation: https://github.com/vuejs/vue-docs-zh-cn/blob/master/vue-cli-plugin-eslint/README.md

       Eslint official rules: https://cn.eslint.org/docs/rules/

1. The syntax rules are written in the rules option in the package.json or. eslintrc.js file. The syntax is as follows:

rules: {
    "Rules":"Error level value, rule configuration"
}

Rule value

"off" Or 0 // Close rule
"warn" Or 1 // Open the rule as a warning message (print in yellow font)
"error" Or 2 // Open the rule as an error message (print in red)

2. Common Eslint rule configuration parameters

"no-alert": 0,//Prohibited use alert confirm prompt
"no-array-constructor": 2,//Array constructors are prohibited
"no-bitwise": 0,//Bitwise operators are prohibited
"no-caller": 1,//Prohibited use arguments.caller or arguments.callee
"no-catch-shadow": 2,//prohibit catch Clause parameter has the same name as an external scope variable
"no-class-assign": 2,//Class assignment is prohibited
"no-cond-assign": 2,//Assignment statements are prohibited in conditional expressions
"no-console": 2,//Prohibited use console
"no-const-assign": 2,//Prohibit modification const Declared variables
"no-constant-condition": 2,//Constant expressions are prohibited in conditions if(true) if(1)
"no-continue": 0,//Prohibited use continue
"no-control-regex": 2,//The use of control characters in regular expressions is prohibited
"no-debugger": 2,//Prohibited use debugger
"no-delete-var": 2,//Not right var Declared variable usage delete Operator
"no-div-regex": 1,//Regular expressions that look like division cannot be used/=foo/
"no-dupe-keys": 2,//Duplicate keys are not allowed when creating object literals {a:1,a:1}
"no-dupe-args": 2,//Function arguments cannot be repeated
"no-duplicate-case": 2,//switch Medium case Labels cannot be repeated
"no-else-return": 2,//If if There are in the statement return,You can't follow else sentence
"no-empty": 2,//The content in a block statement cannot be empty
"no-empty-character-class": 2,//In regular expressions[]Content cannot be empty
"no-empty-label": 2,//Do not use empty label
"no-eq-null": 2,//Prohibition on null use==or!=operator
"no-eval": 1,//Prohibited use eval
"no-ex-assign": 2,//Forbidden to give catch Exception parameter assignment in statement
"no-extend-native": 2,//Prohibit extension native object
"no-extra-bind": 2,//Prohibit unnecessary function binding
"no-extra-boolean-cast": 2,//Prohibit unnecessary bool transformation
"no-extra-parens": 2,//Unnecessary parentheses are prohibited
"no-extra-semi": 2,//Prohibit redundant colons
"no-fallthrough": 1,//prohibit switch pierce through
"no-floating-decimal": 2,//Omitting 0 from floating point numbers is prohibited .5 3.
"no-func-assign": 2,//Duplicate function declarations are prohibited
"no-implicit-coercion": 1,//Prohibit implicit conversion
"no-implied-eval": 2,//Implicit is prohibited eval
"no-inline-comments": 0,//Intra line remarks are prohibited
"no-inner-declarations": [2, "functions"],//The use of declarations (variables or functions) in block statements is prohibited
"no-invalid-regexp": 2,//Invalid regular expressions are prohibited
"no-invalid-this": 2,//Invalid prohibited this,Can only be used in constructors, classes, object literals
"no-irregular-whitespace": 2,//Irregular spaces are not allowed
"no-iterator": 2,//Prohibited use__iterator__ attribute
"no-label-var": 2,//label Name cannot be associated with var The declared variable names are the same
"no-labels": 2,//Prohibition label declaration
"no-lone-blocks": 2,//Unnecessary nested blocks are prohibited
"no-lonely-if": 2,//prohibit else Only if sentence
"no-loop-func": 1,//It is forbidden to use functions in loops (if there is no reference to external variables and no closure is formed)
"no-mixed-requires": [0, false],//Declaration types cannot be mixed when declaring
"no-mixed-spaces-and-tabs": [2, false],//No mixing tab And spaces
"linebreak-style": [0, "windows"],//Line feed style
"no-multi-spaces": 1,//You cannot use extra spaces
"no-multi-str": 2,//String cannot be used\Line feed
"no-multiple-empty-lines": [1, {"max": 2}],//No more than 2 blank lines are allowed
"no-native-reassign": 2,//Cannot override native object
"no-negated-in-lhs": 2,//in The left side of an operator cannot have!
"no-nested-ternary": 0,//Nested ternary operations are prohibited
"no-new": 1,//Prohibited in use new No assignment after constructing an instance
"no-new-func": 1,//Prohibited use new Function
"no-new-object": 2,//Prohibited use new Object()
"no-new-require": 2,//Prohibited use new require
"no-new-wrappers": 2,//Prohibited use new Create a wrapper instance, new String new Boolean new Number
"no-obj-calls": 2,//You cannot call built-in global objects, such as Math() JSON()
"no-octal": 2,//Octal digits are prohibited
"no-octal-escape": 2,//Octal escape sequences are prohibited
"no-param-reassign": 2,//Re assignment of parameters is prohibited
"no-path-concat": 0,//node Cannot be used in__dirname or__filename Do path splicing
"no-plusplus": 0,//Prohibited use++,--
"no-process-env": 0,//Prohibited use process.env
"no-process-exit": 0,//Prohibited use process.exit()
"no-proto": 2,//Prohibited use__proto__attribute
"no-redeclare": 2,//Duplicate declaration of variables is prohibited
"no-regex-spaces": 2,//Multiple spaces are prohibited in regular expression literals /foo bar/
"no-restricted-modules": 0,//If the specified module is disabled, an error will be reported
"no-return-assign": 1,//return Cannot have an assignment expression in a statement
"no-script-url": 0,//Prohibited use javascript:void(0)
"no-self-compare": 2,//Cannot compare itself
"no-sequences": 0,//Comma operators are prohibited
"no-shadow": 2,//A variable in an external scope cannot have the same name as a variable or parameter in the scope it contains
"no-shadow-restricted-names": 2,//The restricted identifier specified in strict mode cannot be used as the variable name at the time of declaration
"no-spaced-func": 2,//Function name and()No spaces between
"no-sparse-arrays": 2,//Sparse arrays are prohibited, [1,,2]
"no-sync": 0,//nodejs Disable synchronization method
"no-ternary": 0,//Ternary operators are prohibited
"no-trailing-spaces": 1,//There should be no spaces after the end of a line
"no-this-before-super": 0,//In call super()Cannot be used before this or super
"no-throw-literal": 2,//Do not throw literal errors throw "error";
"no-undef": 1,//Cannot have undefined variables
"no-undef-init": 2,//When initializing a variable, it cannot be directly assigned to undefined
"no-undefined": 2,//out of commission undefined
"no-unexpected-multiline": 2,//Avoid multiline expressions
"no-underscore-dangle": 1,//Identifier cannot be in_Start or end
"no-unneeded-ternary": 2,//Unnecessary nesting is prohibited var isYes = answer === 1 ? true : false;
"no-unreachable": 2,//There can be no code that cannot be executed
"no-unused-expressions": 2,//Disable useless expressions
"no-unused-vars": [2, {"vars": "all", "args": "after-used"}],//Cannot have variables or parameters that are not used after declaration
"no-use-before-define": 2,//Cannot be used before it is defined
"no-useless-call": 2,//Prohibit unnecessary call and apply
"no-void": 2,//Disable void Operator
"no-var": 0,//Disable var,use let and const replace
"no-warning-comments": [1, { "terms": ["todo", "fixme", "xxx"], "location": "start" }],//Warning remarks are not allowed
"no-with": 2,//Disable with
"array-bracket-spacing": [2, "never"],//Allow extra spaces in non empty arrays
"arrow-parens": 0,//Arrow functions are enclosed in parentheses
"arrow-spacing": 0,//=>Before/Back bracket
"accessor-pairs": 0,//Use in objects getter/setter
"block-scoped-var": 0,//Used in block statements var
"brace-style": [1, "1tbs"],//Brace style
"callback-return": 1,//Avoid calling callbacks many times
"camelcase": 2,//Forced hump naming
"comma-dangle": [2, "never"],//The end of an object literal item cannot have a comma
"comma-spacing": 0,//Space before and after comma
"comma-style": [2, "last"],//Comma style, at the beginning or end of the line when wrapping
"complexity": [0, 11],//Cyclic complexity
"computed-property-spacing": [0, "never"],//Allow calculated key names or something
"consistent-return": 0,//return Is it allowed to omit later
"consistent-this": [2, "that"],//this alias
"constructor-super": 0,//Non derived classes cannot be called super,Derived classes must call super
"curly": [2, "all"],//Must use if(){} Medium{}
"default-case": 2,//switch Statement must end with default
"dot-location": 0,//The position of the object accessor, at the beginning or end of the line when wrapping
"dot-notation": [0, { "allowKeywords": true }],//Avoid unnecessary square brackets
"eol-last": 0,//The file ends with a single line break
"eqeqeq": 2,//Congruence must be used
"func-names": 0,//Function expression must have a name
"func-style": [0, "declaration"],//Function style, which specifies that only function declarations can be used/Function expression
"generator-star-spacing": 0,//generator function *Space before and after
"guard-for-in": 0,//for in Cycle to use if Statement filtering
"handle-callback-err": 0,//nodejs Processing error
"id-length": 0,//Variable name length
"indent": [2, 4],//Indent style 
"init-declarations": 0,//Initial value must be assigned when declaring
"key-spacing": [0, { "beforeColon": false, "afterColon": true }],//Spaces before and after colons in object literals
"lines-around-comment": 0,//Before departure/Remarks after line
"max-depth": [0, 4],//Nested block depth
"max-len": [0, 80, 4],//Maximum string length
"max-nested-callbacks": [0, 2],//Callback nesting depth
"max-params": [0, 3],//A function can have at most 3 arguments
"max-statements": [0, 10],//How many declarations are there at most in a function
"new-cap": 2,//The first line of the function name must be capitalized new Method call, the first line must be in lowercase without new Mode call
"new-parens": 2,//new Parentheses must be added when
"newline-after-var": 2,//Need a blank line after variable declaration
"object-curly-spacing": [0, "never"],//Are unnecessary spaces allowed within braces
"object-shorthand": 0,//Enforce object literal abbreviation syntax
"one-var": 1,//declaration of continuity
"operator-assignment": [0, "always"],//Assignment Operators  += -=What
"operator-linebreak": [2, "after"],//Is the operator at the end of the line or at the beginning of the line when wrapping
"padded-blocks": 0,//Whether the beginning and end of a line in a block statement should be blank
"prefer-const": 0,//be the first choice const
"prefer-spread": 0,//Preferred expansion operation
"prefer-reflect": 0,//be the first choice Reflect Method of
"quotes": [1, "single"],//Quote type `` "" ''
"quote-props":[2, "always"],//Whether double quotes are mandatory for property names in object literals
"radix": 2,//parseInt The second parameter must be specified
"id-match": 0,//Name detection
"require-yield": 0,//Generator function must have yield
"semi": [2, "always"],//Statement force semicolon end
"semi-spacing": [0, {"before": false, "after": true}],//Space before and after semicolon
"sort-vars": 0,//Sort on variable declaration
"space-after-keywords": [0, "always"],//Do you want to leave a space after the keyword
"space-before-blocks": [0, "always"],//A block that does not start with a new line{Is there a space in front
"space-before-function-paren": [0, "always"],//Should there be spaces before parentheses when defining functions
"space-in-parens": [0, "never"],//Are there any spaces in parentheses
"space-infix-ops": 0,//Do you want spaces around infix operators
"space-return-throw-case": 2,//return throw case Do you want a space after it
"space-unary-ops": [0, { "words": true, "nonwords": false }],//Before unary operator/Do you want to add a space after
"spaced-comment": 0,//Does the annotation style have spaces or something
"strict": 2,//Use strict mode
"use-isnan": 2,//Prohibit use when comparing NaN,Only use isNaN()
"valid-jsdoc": 0,//jsdoc rule
"valid-typeof": 2,//Legal must be used typeof Value of
"vars-on-top": 2,//var Must be placed at the top of the scope
"wrap-iife": [2, "inside"],//The parenthesis style of the function expression that executes immediately
"wrap-regex": 0,//Regular expression literals are enclosed in parentheses
"yoda": [2, "never"]//Prohibition of Yoda conditions

 

12.7.4 repair code by rule field

  Executing the following command will check according to the syntax rules defined by Eslint, and automatically repair the non-conforming code in the project according to the syntax rules

npm run lint

 

12.8 create. vue template code

12.8.1 installation plug-in identification vue file

Search the plug-in library for vehicle installation

 

12.8.2 code snippet of configuration template

1. Select "File - > Preferences - > User snippets". A search box will pop up and enter vue.

2. After selecting Vue, VS Code will automatically open a file named vue.json and copy the following contents into this file

{
    "Print to console": {
        "prefix": "vue",
        "body": [
            "<template>",
            "  <div>",
            "    $0",
            "  </div>",
            "</template>",
            "",
            "<script>",
            "export default {",
            "  data () {",
            "    return {",
            "    }",
            "  },",
            "",
            "  components: {},",
            "",
            "  methods: {}",
            "}",
            "</script>",
            "",
            "<style scoped>",
            "</style>"
        ],
        "description": "Log output to console"
    }
}

 

12.9 deployment project

12.9.1 packaged items

npm run build

12.9.2 deployment project

 

Posted by banks1850 on Thu, 04 Nov 2021 14:03:28 -0700