Vue CLI 3 builds the most comprehensive analysis of vue+vuex

1. Introduction

Vue CLI is a complete system for rapid development based on Vue.js. There are three components:

CLI : A@vue/cli globally installed npm package that provides vue commands in the terminal (such as vue create, vue serve, vue ui, etc.)

CLI service :@vue/cli-serviceis a development environment dependency. Built on  top of webpack  and  webpack-dev-server  (provides e.g.serve,build and inspect commands)

CLI plugins : npm packages that provide optional functionality to Vue projects (eg: Babel/TypeScript transpilation, ESLint integration, unit and e2e testing, etc.)

2. Installation

vue-cli1. If an old version (1.x or 2.x) is installed globally,  uninstall it first, otherwise skip this step:

npm uninstall vue-cli -g //或者 yarn global remove vue-cli

The operation is as follows:

You can see that my previous version is 2.9.6. After the uninstallation is successful, the vue command does not exist.

ps: npm WARN warning, maybe a dependency package of coffee-script has been renamed (coffee-script itself has been eliminated)

2. Vue CLI 3 requires nodeJs ≥ 8.9 (8.11.0+ is officially recommended, you can use  nvm  or  nvm-windows to manage multiple Node versions on the same computer).

(1) Check the node version

(2) It is very simple to download and install nodeJs (as with other system software, install it according to the requirements), which will not be introduced here. The official Chinese download address: http://nodejs.cn/download/ 

3. Install @vue/cli (the package name of Vue CLI 3 has been  vue-cli changed to  @vue/cli)

cnpm install -g @vue/cli  //yarn global add @vue/cli

The operation is as follows:

View version:

vue -V //vue --version

The result is as follows:

3. Use

1. Vue create builds a new project

(1) New project:

*Official tip: If you are using Git Bash via minTTY on Windows, the interactive prompt does not work, you must  winpty vue.cmd create hello-world start this command by

vue create <Project Name> //文件名 不支持驼峰(含大写字母)

The specific operations are as follows:

First, you will be prompted to choose a preset:

① Except for the last two , the other options are the preset configurations you saved before (the first "preset-config" in the figure below is the preset configuration I saved before, and it can be used directly now):

If no configuration has been saved, there are only two options:

② default(babel,eslint):

The default settings (enter directly) are great for quickly prototyping a new project, no npm packages with any helper features

③ Manually select features:

Manual configuration (press the arrow key ↓) is a production-oriented project we need, an npm package that provides optional functions

 

Manual configuration, use the arrow keys to select the corresponding function according to your needs (press the "space bar" to select/cancel selection, A key to select all/cancel all selections)

Introduction:

? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection)
>( ) Babel                           //转码器,可以将ES6代码转为ES5代码,从而在现有环境执行。                      
 ( ) TypeScript// TypeScript是一个JavaScript(后缀.js)的超集(后缀.ts)包含并扩展了 JavaScript 的语法,需要被编译输出为 JavaScript在浏览器运行,目前较少人再用
 ( ) Progressive Web App (PWA) Support// 渐进式Web应用程序
 ( ) Router                           // vue-router(vue路由)
 ( ) Vuex                             // vuex(vue的状态管理模式)
 ( ) CSS Pre-processors               // CSS 预处理器(如:less、sass)
 ( ) Linter / Formatter               // 代码风格检查和格式化(如:ESlint)
 ( ) Unit Testing                     // 单元测试(unit tests)
 ( ) E2E Testing                      // e2e(end to end) 测试

After selecting, enter directly, and then you will be prompted to select the specific toolkit for the corresponding function, and choose the one you are good at or widely used (for Baidu when you encounter problems). The introduction is as follows:

①Whether to use history router:

Vue-Router utilizes the features of the browser's own hash mode and history mode to implement front-end routing (by calling the interface provided by the browser)

hash:  The # symbol in the browser url address bar (such as this URL: http://www.abc.com/#/hello, the hash value is "#/hello"), the hash is not included in the HTTP request ( has no effect on the backend at all), so changing the hash won't reload the page

history: Take advantage of the new pushState( ) and replaceState( ) methods in the HTML5 History Interface (requires specific browser support). For single-page client applications, history mode requires background configuration support (for details, see: https://router.vuejs.org/zh/guide/essentials/history-mode.html )

② css preprocessor

It mainly solves problems such as browser compatibility and simplification of CSS code for CSS ( * Sass was born in 2007, the earliest and most mature CSS preprocessor language. )

? Please pick a preset: Manually select features
? Check the features needed for your project: Router, Vuex, CSS Pre-processors, Linter, Unit
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default):
> SCSS/SASS  //Sass安装需要Ruby环境,是在服务端处理的,SCSS 是 Sass3新语法(完全兼容 CSS3且继承Sass功能)
  LESS       //Less最终会通过编译处理输出css到浏览器,Less 既可以在客户端上运行,也可在服务端运行 (借助 Node.js)
  Stylus     //Stylus主要用来给Node项目进行CSS预处理支持,Stylus功能上更为强壮,和js联系更加紧密,可创建健壮的、动态的的CSS。

ESLint

Provide a plug-in javascript code detection tool

? Pick a linter / formatter config: (Use arrow keys)
> ESLint with error prevention only
  ESLint + Airbnb config
  ESLint + Standard config
  ESLint + Prettier         //使用较多

④ When to detect:

? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
>( ) Lint on save                    // 保存就检测
 ( ) Lint and fix on commit          // fix和commit时候检查

⑤ Unit testing:

? Pick a unit testing solution: (Use arrow keys)
> Mocha + Chai  //mocha灵活,只提供简单的测试结构,如果需要其他功能需要添加其他库/插件完成。必须在全局环境中安装
  Jest          //安装配置简单,容易上手。内置Istanbul,可以查看到测试覆盖率,相较于Mocha:配置简洁、测试代码简洁、易于和babel集成、内置丰富的expect

⑥ How to store the configuration:

? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? (Use arrow keys)
> In dedicated config files // 独立文件放置
  In package.json // 放package.json里

 ⑦ Whether to save this configuration (you can use it directly later):

? Save this as a preset for future projects? (Y/n) // y:记录本次配置,然后需要你起个名; n:不记录本次配置

(2) Construction is complete:

The project structure is as follows (different presets contain different files, roughly the same structure):

Compare with previous packages:

vs

The only thing left is the soul~ The main big differences are as follows:

① vuex (state management):

In vue cli 2  : vuex is installed by itself after the construction is completed, and it is not included in the construction process. You can see that the vuex default folder (store) of vue cli 2 contains three js files: action (store some asynchronous execution methods that call external API interfaces, and then commit mutations to change the mutations data), index (initialize the mutations data) , is the outlet of the store), mutations (a collection of methods that process the synchronous execution of data logic , the only way to change the store data in Vuex commit mutations)

In vue cli 3 : vuex is an optional preset included in the build process. In vue cli 3, only one store.js is used by default to replace the three js files in the original store folder. There are many usages of action, mutations, state, and store getters. Here are some common examples:

eg:store.js

import Vue from 'vue';
import Vuex from 'vuex'; //引入 vuex
import store from './store' //注册store

Vue.use(Vuex); //使用 vuex

export default new Vuex.Store({
    state: {
        // 初始化状态
        count: 0
    },
    mutations: {
        // 处理状态
        increment(state, payload) {
            state.count += payload.step || 1;
        }
    },
    actions: {
        // 提交改变后的状态
        increment(context, param) {
            context.state.count += param.step;
            context.commit('increment', context.state.count)//提交改变后的state.count值
        },
        incrementStep({state, commit, rootState}) {
            if (rootState.count < 100) {
                store.dispatch('increment', {//调用increment()方法
                    step: 10
                })
            }
        }
    }
})

When used, eg:

main.js:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store' //引入状态管理 store

Vue.config.productionTip = false

new Vue({
  router,
  store,//注册store(这可以把 store 的实例注入所有的子组件)
  render: h => h(App)
}).$mount('#app')

views/home.vue:

<template>
    <div class="home">
      <!--在前端HTML页面中使用 count-->
        <HelloWorld :msg="count"/>
    </div>
</template>

<script>
    import HelloWorld from '@/components/HelloWorld.vue'
    import {mapActions, mapState} from 'vuex' //注册 action 和 state

    export default {
        name: 'home',
        computed: {
            //在这里映射 store.state.count,使用方法和 computed 里的其他属性一样
            ...mapState([
                'count' 
            ]),
        },
        created() {
            this.incrementStep();
        },
        methods: {
            //在这里引入 action 里的方法,使用方法和 methods 里的其他方法一样
            ...mapActions([
                'incrementStep'
            ]),
        },
        components: {
            HelloWorld
        }
    }
</script>

② router:

vue cli 2 :“ router/index.js ”

vue cli 3: "router.js" (uses and does the same thing)

③ Remove static and add public folder

vue cli 2  : static is the default folder for webpack to store static resources. When packaging, it will directly copy a copy to the dist folder without compiling through webpack 

vue cli 3  : Abandon static and add public . There are two processing methods for "static resources" in vue cli 3:

  • Processed by webpack: Assets imported in JavaScript or referenced via "relative paths" in templates/CSS are compiled and minified

  • Not processed by webpack:  public resources placed in a directory or referenced by an absolute path will be "directly copied" without any compilation and compression

④ index.html :

vue cli 2 :“index.html ” 

v ue cli 3  : "public/index.html" this template will be   processed by html-webpack-plugin

⑤ src/views:

The src folder of vue cli 3 adds a views folder to store "pages", distinguishing components (components)

⑥ Remove the build (define rules according to the configuration in config) and config (configure parameters of different environments) folders:

 In vue cli 3  , you can configure the development server through command line parameters, or  vue.config.js (create a new vue.config.js file with the same name in the root directory) in the  devServer  field. 

⑦ babel.config.js:

Configure Babel. The Vue CLI uses the new configuration format in Babel 7  babel.config.js. Unlike   the  fields in .babelrc or   , this configuration file will not use a file location-based scheme, but will consistently apply to all files below the project root, including   internal dependencies. The official recommendation is to always use   over other formats in Vue CLI projects.package.jsonbabelnode_modulesbabel.config.js

⑧ Changes of some other files in the root directory:

All the previous configuration files are preset when the vue create is built or can pass command parameters, vue.config.js 中配置

根据需要在根目录下新建 vue.config.js自行配置,eg:(简单配置,更多配置详情参见官网:https://cli.vuejs.org/zh/config/

module.exports = {
    baseUrl: '/',// 部署应用时的根路径(默认'/'),也可用相对路径(存在使用限制)
    outputDir: 'dist',// 运行时生成的生产环境构建文件的目录(默认''dist'',构建之前会被清除)
    assetsDir: '',//放置生成的静态资源(s、css、img、fonts)的(相对于 outputDir 的)目录(默认'')
    indexPath: 'index.html',//指定生成的 index.html 的输出路径(相对于 outputDir)也可以是一个绝对路径。
    pages: {//pages 里配置的路径和文件名在你的文档目录必须存在 否则启动服务会报错
        index: {//除了 entry 之外都是可选的
            entry: 'src/index/main.js',// page 的入口,每个“page”应该有一个对应的 JavaScript 入口文件
            template: 'public/index.html',// 模板来源
            filename: 'index.html',// 在 dist/index.html 的输出
            title: 'Index Page',// 当使用 title 选项时,在 template 中使用:<title><%= htmlWebpackPlugin.options.title %></title>
            chunks: ['chunk-vendors', 'chunk-common', 'index'] // 在这个页面中包含的块,默认情况下会包含,提取出来的通用 chunk 和 vendor chunk
        },
        subpage: 'src/subpage/main.js'//官方解释:当使用只有入口的字符串格式时,模板会被推导为'public/subpage.html',若找不到就回退到'public/index.html',输出文件名会被推导为'subpage.html'
    },
    lintOnSave: true,// 是否在保存的时候检查
    productionSourceMap: true,// 生产环境是否生成 sourceMap 文件
    css: {
        extract: true,// 是否使用css分离插件 ExtractTextPlugin
        sourceMap: false,// 开启 CSS source maps
        loaderOptions: {},// css预设器配置项
        modules: false// 启用 CSS modules for all css / pre-processor files.
    },
    devServer: {// 环境配置
        host: 'localhost',
        port: 8080,
        https: false,
        hotOnly: false,
        open: true, //配置自动启动浏览器
        proxy: {// 配置多个代理(配置一个 proxy: 'http://localhost:4000' )
            '/api': {
                target: '<url>',
                ws: true,
                changeOrigin: true
            },
            '/foo': {
                target: '<other_url>'
            }
        }
    },
    pluginOptions: {// 第三方插件配置
        // ...
    }
};

(3) npm run serve runs~

webstorm opens the project (personal habits, you can also run it directly after setting up), after running, webstorm automatically generates an .idea file (used to store the configuration information of the project, such as version control information, history records, etc.)

(4) View the running results:

Open the browser, enter the address prompted by the running result (the red box in the above picture), enter

(5) Pull the 2.x template (old version):

Vue CLI 3 overwrites the old version of the vue command, if you need to use the old version of the  vue init function, you can install a bridge tool globally:

npm install -g @vue/cli-init //`vue init` 的运行效果将会跟 `[email protected]` 相同
vue init webpack my-project

(6) Install the plugin (vue add command) in the existing project, eg:

*Official tip: vue add The design intent is to install and invoke the Vue CLI plugin. This is not meant to replace normal npm packages. For these normal npm packages, you still need to choose a package manager

! Official Warning: We recommend committing the latest state of your project before running  vue add , as this command may invoke the plugin's file generator and most likely change your existing files.

vue add @vue/eslint //如果不带 @vue 前缀,该命令会换作解析一个 unscoped 的包,你也可以基于一个指定的 scope 使用(eg:vue add @foo/bar)

2, vue ui graphical interface to create projects

vue ui

Enter the command on the command line as follows:

Then it will automatically open the browser page and choose to create as follows:

The result is as follows:

The page prompts that dependencies are being installed:

There are already project packages locally:

Installation is complete: you can manage (install, delete) plugins, run and analyze your project files here

 

If you want to know about vue cli 2, see my blog:  https://my.oschina.net/wangnian/blog/2050375

To understand node and npm installation/update/use, see my blog: https://my.oschina.net/wangnian/blog/2032386

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324164652&siteId=291194637