# Vue CLI

官方简介:

vue-cli (opens new window) 是 Vue.js 开发的标准工具。程序员可以专注在撰写应用上,而不必花好几天去纠结配置的问题。

# 一、vue-cli 入门

# vue-cli安装
npm i @vue/cli -g

# 升级全局的 Vue CLI
npm update @vue/cli -g

# 1、vue-cli 命令

# 查看所用命令
vue --help

常用命令:

提示

  关于 inspect:检查 webpack 配置

不仅仅可以通过 vue inspect 命令查看,还可以通过 vue ui 在控制台页面的任务部分查看。

vue -V # 查看当前项目vue版本

vue create my-project # 创建项目

vue add eslint # 在创建好的项目中安装插件并进行调试
vue invoke eslint # 对已安装好的插件进行调试

vue inspect > output.txt # 在项目中输出webpack默认配置文件
vue server # 等效于 npm run serve
vue build # 等效于 npm run build

vue ui # 创建项目

vue upgrade @vue/cli-plugin-babel@4.5.13  # 升级项目中的某个Vue CLI模块
# 安装Vue CLI2版本
npm install -g @vue/cli-init
vue init webpack my-project

其他命令自己尝试 👀

# 2、vue 项目构建

构建项目:

提示

↑ ↓ 选择、空格键选中、Ent 键下一步

默认构建(Default)

babel、eslint

自定义构建(Manually select features)

(*) Babel  兼容性
( ) TypeScript  TS
( ) Progressive Web App (PWA) Support
( ) Router  路由
( ) Vuex  Vuex
(*) CSS Pre-processors  预处理器
( ) Linter / Formatter  代码格式校验
( ) Unit Testing
( ) E2E Testing

项目结构

vue-cli_project
├─ public
│  ├─ favicon.ico
│  └─ index.html🤔
├─ src
│  ├─ App.vue🤔(根组件)
│  └─ main.js🚩(入口文件)
├─ package.json
├─ vue.config.js
└─ README.md

# 3、运行流程

  通过入口文件 —— main.jsApp.vue渲染到index.html的指定区域中。

① main.js

  将根组件 App.vue 的结构覆盖到 index.html 默认的<div id="app"></div> —— render 属性。

② public/index.html

<body>
  <!-- 1、App.vue组件内容会将其覆盖 -->
  <div id="app"></div>

  <!-- 2、将所需要的css、js等等文件自动注入 -->
  <!-- built files will be auto injected -->
</body>

  通过右键查看源码,可以发现页面自动注入了打包生成的 js 文件,类似于 webpack 中的 html-webpack-plugin 辅助插件。

<script defer src="/js/chunk-vendors.js"></script>
<script defer src="/js/app.js"></script>

思考?

如果生成的 js 文件中包含 new Vue 实例 🤔

上述自动注入的 js 文件是什么呢?

  为 vue-cli 内的vue-template-compiler插件编译生成的。其中 app.js 为.vue 等文件编译而来;chunk-vendors.js 为第三方模块打包生成而来。

# 4、版本对比

  • Vue CLI >= 3 项目结构
vue-cli_project
├─ public ✔
│  ├─ favicon.ico
│  └─ index.html 👀
├─ src
│  ├─ assets文件夹
│  ├─ components文件夹
│  ├─ router
│  ├─ store ✨
│  ├─ views ✨
│  ├─ App.vue
│  └─ main.js
├─ package-lock.json
├─ package.json
├─ vue.config.js ✔
└─ README.md
  • Vue CLI <= 2 项目结构
vue-cli_project
├─ build文件夹 ✔
├─ config文件夹 ✔
├─ static ✔
│  └─ .gitkeep
├─ src
│  ├─ assets文件夹
│  ├─ components文件夹
│  ├─ router
│  ├─ App.vue
│  └─ main.js
├─ package-lock.json
├─ package.json
├─ index.html 👀
└─ README.md

  通过构建项目的结构,我们可以发现它们之间的不同:

  • build、config 文件夹 ——> vue.config.js
  • static 文件夹 ——> public 文件夹
  • vue-cli 新版本在构建项目时,新增了TypeScriptVuexCSS Pre-processors选项

# 5、文件大小占比

  要查看该页面,先安装:

npm install webpack-bundle-analyzer -D

  然后在 vue.config.js 中进行配置:

module.exports = {
  devServer: {
    open: true
  },

  chainWebpack: (config) => {
    // 查看打包文件体积大小
    config
      .plugin('webpack-bundle-analyzer')
      .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
  }
}

  分析报告页面默认在:http://127.0.0.1:8888 打开,如果端口被占用,该怎么办?

答案
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

module.exports = {
  devServer: {
    open: true
  },

  chainWebpack: (config) => {
    // 查看打包文件体积大小
    config.plugin('webpack-bundle-analyzer').use(new BundleAnalyzerPlugin({ analyzerPort: 7888 }))
  }
}

# 二、vue.config.js

  在创建好 vue2 项目后,默认会自动生成一个 vue.config.js 文件,内容如下:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true
})

  在项目开发中,我们通常就手动进行一些配置:

基本配置汇总
module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? '/my-app/' : '/'

  outputDir: 'dist-Lencamo',
  assetsDir: 'static',

  devServer: {
    open: true,
    host: 'localhost',
    port: 8081,
    https: false,

    proxy: {
      '/ren': {
        target: 'https://api.example.com',
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/ren': ''
        }
      }
    }
  },

  runtimeCompiler: true, // 是否可以在 Vue 组件中使用 template 选项
  productionSourceMap: false, // 是否在生产环境下使用soruceMap(安全性)(表现为:生产环境下不在产生xxx.js.map文件)
  parallel:require('os').cpus().length > 1, // cpu核数大于 1是启用并行压缩

  // https://github.com/survivejs/webpack-merge
  configureWebpack: {
    // 合并项目中webpack默认配置
    plugins:[],
    module: {
      rules:[]
    }
  },

  // https://github.com/neutrinojs/webpack-chain
  chainWebpack: config => {
    // 修改项目中webpack默认配置
  },

  pluginOptions: {
    // 第三方插件
  },

  pages: {
    index: {
      // page 的入口
      entry: 'src/index/main.js',
      // 模板来源
      template: 'public/index.html',
      // 在 dist/index.html 的输出
      filename: 'index.html',
      // 当使用 title 选项时,
      // template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
      title: 'Index Page',
      // 在这个页面中包含的块,默认情况下会包含
      // 提取出来的通用 chunk 和 vendor chunk。
      chunks: ['chunk-vendors', 'chunk-common', 'index']
    }
  }
}

# 1、publicPath

提示

baseUrl 从 Vue CLI 3.3 起已弃用,请使用 publicPath。

publicPath 的用法和 webpack 本身的 output.publicPath 一致

  -在 hash 模式下,路由不需要知道 publicPath 的值,也不需要设置 base 选项

  下面看看,在 history 模式下,base 选项会进行如下配置:

# ①、常规使用

  默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上。

vue-router 的 base 默认是'/',不需要变动

  如果如果应用程序部署在 /my-app/ 目录下,你就需要用这个选项指定这个子路径。

vue-router 的 base 要配置为:'/my-app/',需要变动

// vue-cli 配置
module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? '/my-app/' : '/'
}

// vue-router 配置
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

# ②、相对路径 ✍

  当我们使用相对路径'./'时,我们的应用可以部署在任意路径上。

vue-router 的 base 要配置为:'./',需要变动

// vue-cli 配置
module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? './' : '/'
}

// vue-router 配置
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

# ③、总结

  如果 publicPath 配置为绝对路径或使用 CDN 地址,那么在路由和 HTML 中使用 URL 时,也需要相应地考虑到绝对路径或 CDN 地址。

在实际项目中,通常需要保证 base 选项和 publicPath 的值相同,以确保路由和静态资源能够正确地访问和加载。


// 动态生成 URL
this.$router.push(`${process.env.BASE_URL}/path/to/somewhere`)

// 引用静态资源
<img src="${process.env.BASE_URL}/assets/logo.png" />

# 2、outputDir/assetsDir

提示

outputDir 的用法和 webpack 本身的 output.path 一致,默认值为 'dist'

当运行 vue-cli-service build 时生成的生产环境构建文件的目录

提示

assetsDir 的用法和 webpack 本身的 output.assetsSubDirectory 一致,默认值为 ''

放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录。

# 3、lintOnSave

  lintOnSave 是 Vue CLI 中用于开启 ESLint 检查的配置项,其默认值为 true。对应构建项目时:

(*) Linter / Formatter  代码格式校验

然后就可以看到对应的选项:

? Pick a linter / formatter config: (Use arrow keys)

  • ESLint with error prevention only
    ESLint + Airbnb config
    ESLint + Standard config
    ESLint + Prettier

  这个配置表示:是否在开发环境下通过 eslint-loader 在每次保存时 lint 代码。这个值会在 @vue/cli-plugin-eslint 被安装之后生效。

module.exports = {
  lintOnSave: process.env.NODE_ENV === 'development'
}

  下面来描述几个注意事项:

查看答案
  • 项目中安装了 ESLint 相关的依赖 并且 构建项目时选择了 ESLint 检查,lintOnSave 配置才能生效。
  • 若项目中使用了 TypeScript,并且安装了 @vue/cli-plugin-typescript 插件,那么 lintOnSave 配置项会被忽略

  更多的,如果我们要将 ESLint 和 Prettier / Typescript 配合使用时,要在.eslintrc.js 中添加配置:

module.exports = {
  extends: [
    'plugin:vue/vue3-essential',
    'eslint:recommended',
    '@vue/typescript/recommended', // 和typescript
    'plugin:prettier/recommended' // 和Prettier
  ]
}

# 4、devServer

  所有 webpack-dev-server (opens new window) 的选项都支持。并且还可以使用 devServer.proxy 选项来进行代理转发。

其本质是使用了http-proxy-middleware (opens new window) 中间件 (opens new window),说白了还是使用了 CORS 方式解决跨域 (opens new window)的。

module.exports = {
  devServer: {
    // 一、项目启动配置
    open: true,
    host: 'localhost',
    port: 8081, // 默认为8080
    https: false,

    // 二、请求代理配置
    proxy: {
      '/ren': {
        target: 'https://api.example.com',
        ws: true, // 支持webSocket
        // 请求头的 Host 字段将由http://localhost:8080改为http://localhost:6061(伪装)
        changeOrigin: true,
        // 将 https://api.example.com/ren/data/ 代理到 https://api.example.com/data/
        // 【去掉/ren这个接口标识】
        pathRewrite: {
          '^/ren': ''
        }
      }
      // '/foo': {
      //   target: '<other_url>'
      // }
    }
  }
}

# 5、configureWebpack

module.exports = {
  configureWebpack: {
    //  这个是设置外部扩展,模块为qc变量名为QC,导入qc将不做打包
    externals: {
      qc: 'QC' // 遇到 import 'qc' 不要去node_modules下找了
    }
  }
}

# 6、chainWebpack

更新于 : 8/7/2024, 2:16:31 PM