Vue – An official CLI document

Vue – CLI setup project creation and general configuration

Project creation

Note: You need a Node environment, so remember to install NodeJS

Environmental win10

  $ npm -v
  6.13.4
  
  $ node -v
  v12.16.0
  $ vue -V @ vue/cli 4.4.6Copy the code

Install the Vue command-line tool globally

    npm install -g @vue/cli
    
// After the installation, run the following command to view the version description    
    vue -V
 @ vue/cli 4.4.6Copy the code

Create a project

Run the vue create project name command

$vue create The name of the project    
? Please pick a preset: (use arrow keys)      default (babel, eslint)  
> Manually select features // Enter Copy the code

After the Enter, enter the manual selection configuration. The following Installed CLI Plugins option is displayed. (Note: Select a for all and I for all)

   ? Please pick a preset: Manually select features
   ? Check the features needed for your project: 
(*) Babel// Syntax compilation is backward compatible    ( ) TypeScript // .ts
(*) Progressive Web App (PWA) Support(*) Router // Route(*) Vuex // State management(*) CSS pre-processors // CSS preprocessors(*) Linter/Formatter // Syntax check>(*) Unit Testing //() E2E Testing // Integration Testing from the user's perspectiveCopy the code

Select whether the route is in history mode

    ? Please pick a preset: Manually select features
    ? Check the features needed for your project: Babel, PWA, Router, Vuex, CSS Pre-processors, Linter, Unit, E2E
    ? Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n) Y
Copy the code

Select Select a CSS preprocessor

  ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): (Use arrow keys)
  > Sass/SCSS (with dart-sass)
    Sass/SCSS (with node-sass)
    Less
    Stylus
Copy the code

Select code validation

    ? Pick a linter / formatter config: (Use arrow keys)
      ESLint with error prevention only
      ESLint + Airbnb config
      ESLint + Standard config
> ESLint + Prettier (code validation + style)Copy the code

Select Save to check the code

    ? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
    >(*) Lint on save
     ( ) Lint and fix on commit
Copy the code

Select the unit test solution Jest

    ? Pick a unit testing solution: 
      Mocha + Chai
    > Jest
Copy the code

Select an E2E test solution Cypress

   ? Pick a E2E testing solution: (Use arrow keys)
   > Cypress (Chrome only)
     Nightwatch (WebDriver-based)
Copy the code

Select a dedicated profile for the configuration

    ? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? (Use arrow keys)
    > In dedicated config files
      In package.json
Copy the code

Save the configuration

    ? Save this as a preset for future projects? (y/N) Y
    ? Save preset as: test// Save the default as a specified name    
// Then load the default configuration directly when creating the project// For example, vue create --presettest test
Copy the code

After the creation, enter the project and run the following command to run the project

    cdProject /    npm run serve
Copy the code

Directory description

├─ Node_modules // NPM├ ─ public│ ├ ─index.html │ ├ ─index.html│ └ ─ img│ └ ─ the ICONS├ ─ SRC│ ├─ Assets // Assets│ ├─ Components // Public components│ ├─ Bass Exercises│ ├─ Bass Exercises│ ├─ Bass Exercises // Views│ ├─ Active.vue // The main component of the project│ ├─ Main.js // Vue example│ ├ ─ registerServiceworker.js├─.Browserslistrc // Browser compatibility.eslintrc.js // Code detection tool.eslintignore // Configure code to detect ignored files.gitignore // Git ignore file configuration├─ Babel.config.js // Toolchain syntax compilation is backward compatibleJson // Basic module information The version of the module required for project development project name├─ Package-locking. json // NPM install. Record the actual version and source of the NPM package installed├─ Vue.config.js // A file for storing vue configurations. You can use it to set up proxies, package configurations, etc. (you need to create your own)├─ Tests // Unit tests│ └ ─ unit│ ├ ─example.spec.js├─ Jest.config.js // Unit test configurationReadme.md // Project description document in Markdown format.env // is loaded in all environments, but has the lowest priority.├─.env.development // Development Environment Configuration├─.env.test // Test Environment Configuration (to be created by yourself)├─.env.production // Production environment ConfigurationCopy the code

The basic configuration

Environment variables and patterns

The environment variable

You can create configuration files in the project root directory

The configuration file creation and loading rules are as follows

    .env                # is loaded in all environments
    .env.local          # is loaded in all environments but is ignored by Git
    .env.[mode]         # is loaded only in the specified mode
    .env.[mode].local   # is only loaded in the specified schema, but is ignored by Git
Copy the code

The contents of an environment profile contain only key = value pairs of environment variables:

  VUE_APP_SECRET=secret
  VUE_APP_BASE_API = http://192.168.0.151/login
Copy the code

model

Patterns are an important concept in the Vue CLI project. By default, a Vue CLI project has three modes:

  • The development mode is used in vue-cli-service serve // development environment
  • Production mode for vue-cli-service build and vue-cli-service test: E2E // Production environment (official environment)
  • The test mode is used in vue-cli-service test:unit // test environment

This function is to facilitate the actual needs of the project development process, such as: different environment interface address may be different

–mode specifies the mode of the package.json file

    "scripts": {
        "serve": "vue-cli-service serve", // The default reads the configuration of.env.development        "test": "vue-cli-service serve --mode test", // .env.test
        "production": "vue-cli-service serve --mode production",  // .env.production
        "build:dev": "vue-cli-service build --mode development",  // .env.development
 "build:test": "vue-cli-service build --mode test", // .env.test  "build": "vue-cli-service build", // The default read configuration of.env.production "test:unit": "vue-cli-service test:unit". "lint": "vue-cli-service lint"  }, Copy the code

Environment variables and patterns

Code lint

ESLint website

env

extends

rules

configuration

.eslintrc.js

    module.exports = {
// Restrict items to the current directory      root: true.// Available environment variables      env: {
 browser: true, // Global variables in the browser environment node: true, // node.js global variable and node.js scope. es6: true// Enable all ECMAScript 6 features except Modules }, // Inheritance rules extends: ["plugin:vue/essential"."eslint:recommended"."@vue/prettier"]. parserOptions: {  parser: "babel-eslint"  }, // Define rules rules: {  "no-console": process.env.NODE_ENV === "production" ? "warn" : "off", // Whether to disable console "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off"// Whether to disable debugger. // More rules can be configured according to the actual needs of your project }, // Specify processors for unit testing specific types of files overrides: [  {  files: [  "**/__tests__/*.{j,t}s? (x)". "**/tests/unit/**/*.spec.{j,t}s? (x)" ]. env: {  jest: true  }  }  ]  }; Copy the code

.eslintignore

    build/*.js
    
    src/assets
    
    public
Copy the code

Visual Studio Code + ESLint

After.eslintrc.js is configured

Open Visual Studio Code to download the plug-in

vue.config.js

Detailed configuration Description


    "use strict";
    const path = require("path");
    
    function resolve(dir) {
 return path.join(__dirname, dir);  }   const name = "iwhao simple"; // title The title of the website // Default port// The non-root user on the MAC cannot use the common ports smaller than 1024 to run the NPM Run Serve const port = process.env.port || process.env.npm_config_port || 80;   module.exports = {  publicPath: "/", // site root directory path outputDir: "dist", // The directory of the production build files assetsDir: "static", // the directory where the generated static resources are placed lintOnSave: process.env.NODE_ENV === "development". productionSourceMap: false, // if you don't need the production environmentsourceMap, which can be set tofalseTo speed up production build devServer: { Port: port, // port open: true, // Whether to automatically open the browser after running// Displays full-screen overwrite in the browser when a compiler error or warning occurs. Whether to display warnings and errors: overlay: {  warnings: false/ / warningerrors: process.env.ENV ! = ="master"/ / error }  },  configureWebpack: { Name: name, // the name of the site title resolve: {  alias: {  "@": resolve("src") // import The '@'The equivalent of the import'/src'  }  }  }, // Configure for more fine-grained changes chainWebpack(config) {  config.plugins.delete("preload");  config.plugins.delete("prefetch");   // set svg-sprite-loader  config.module  .rule("svg")  .exclude.add(resolve("src/icons"))  .end();  config.module  .rule("icons")  .test(/\.svg$/)  .include.add(resolve("src/icons"))  .end()  .use("svg-sprite-loader")  .loader("svg-sprite-loader")  .options({  symbolId: "icon-[name]"  })  .end();   // set preserveWhitespace  config.module  .rule("vue")  .use("vue-loader")  .loader("vue-loader")  .tap(options => {  options.compilerOptions.preserveWhitespace = true;  return options;  })  .end();   config  // https://webpack.js.org/configuration/devtool/#development  .when(process.env.NODE_ENV === "development", config =>  config.devtool("cheap-source-map")  );  config.when(process.env.NODE_ENV ! = ="development", config => {  config  .plugin("ScriptExtHtmlWebpackPlugin")  .after("html")  .use("script-ext-html-webpack-plugin"[ {  // `runtime` must same as runtimeChunk name. default is `runtime` inline: /runtime\.. *\.js$/ }  ])  .end();  config.optimization.splitChunks({  chunks: "all". cacheGroups: {  libs: {  name: "chunk-libs". test: /[\\/]node_modules[\\/]/,  priority: 10,  chunks: "initial" // only package third parties that are initially dependent  },  elementUI: {  name: "chunk-elementUI", // split elementUI into a single package  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app  test: /[\\/]node_modules[\\/]_? element-ui(.*)/ //in order to adapt to cnpm  },  commons: {  name: "chunk-commons". test: resolve("src/components"), // can customize your rules  minChunks: 3, // minimum common number  priority: 5,  reuseExistingChunk: true  }  }  });  config.optimization.runtimeChunk("single");  });  }  }; Copy the code

My blog

I’m the nuggets

My Jane books

Laravel China

My wechat official account