其余章节请看:javascript
vue 快速入门 系列css
在 vue loader 一文中咱们已经学会从零搭建一个简单的,用于单文件组件开发的脚手架;本篇,咱们将全面学习 vue-cli 这个官方的、成熟的脚手架。html
分上下两篇进行,上篇主要是”基础“
,下篇主要是“开发”
vue
Tip:介绍顺序尽量保持与官方文档一致java
vue-cli 是一个基于 vue.js 进行快速开发的完整系统。node
让咱们专一在撰写应用上,而没必要花好几天去纠结配置的问题。jquery
Vue CLI 有几个独立的部分:cli
、cli 服务
和cli 插件
。webpack
CLI (@vue/cli) 是一个全局安装的 npm 包,提供了终端里的 vue
命令。ios
能够经过 vue create
(下文将会详细介绍) 快速搭建一个新项目。git
CLI 服务 (@vue/cli-service
) 是一个开发环境依赖。它是一个 npm 包,局部安装在每一个 @vue/cli
建立的项目中。
CLI 服务是构建于 webpack
和 webpack-dev-server
之上的。它包含了:
serve
、build
和 inspect
命令。CLI 插件是向你的 Vue 项目提供可选功能的 npm 包,例如 Babel/TypeScript 转译、ESLint 集成、单元测试和 end-to-end 测试等。Vue CLI 插件的名字以 @vue/cli-plugin-
(内建插件) 或 vue-cli-plugin-
(社区插件) 开头,很是容易使用。
当你在项目内部运行 vue-cli-service 命令时,它会自动解析并加载 package.json 中列出的全部 CLI 插件。
插件能够做为项目建立过程的一部分,或在后期加入到项目中,也能够被归成一组可复用的预设(preset
)。
全局安装 @vue/cli 这个包:
> npm install -g @vue/cli
你能够经过简单运行 vue
,看看是否展现出了一份全部可用命令的帮助信息,来验证它是否安装成功。你还能够用这个命令来检查其版本是否正确。请看示例:
// 验证是否安装成功 > vue Usage: vue <command> [options] Options: -h, --help output usage information ...
// 查看版本 > vue --version @vue/cli 4.5.13
如需升级全局的 Vue CLI 包,请运行:
npm update -g @vue/cli
若需升级项目中的 Vue CLI 相关模块(以 @vue/cli-plugin-
或 vue-cli-plugin-
开头),请在项目目录下运行 vue upgrade
:
用法: upgrade [options] [plugin-name] (试用)升级 Vue CLI 服务及插件 选项: -t, --to <version> 升级 <plugin-name> 到指定的版本 -f, --from <version> 跳过本地版本检测,默认插件是今后处指定的版本升级上来 -r, --registry <url> 使用指定的 registry 地址安装依赖 --all 升级全部的插件 --next 检查插件新版本时,包括 alpha/beta/rc 版本在内 -h, --help 输出帮助内容
你可使用 vue serve
和 vue build
命令对单个 *.vue
文件进行快速原型开发,不过这须要先额外安装一个全局的扩展:
> npm install -g @vue/cli-service-global
vue serve
的缺点就是它须要安装全局依赖,这使得它在不一样机器上的一致性不能获得保证。所以这只适用于快速原型开发。
你所须要的仅仅是一个 App.vue 文件。
请看示例:
建立目录 demo,新建 App.vue 文件:
// demo/App.vue <template> <h1>Hello!</h1> </template>
而后在这个 App.vue 文件所在的目录下运行:
demo> vue serve App running at: - Local: http://localhost:8080/ - Network: http://192.168.0.103:8080/
访问 http://localhost:8080/
,页面显示 Hello,并有热模块替换功能。
vue serve
使用了和 vue create
建立的项目相同的默认设置 (webpack、Babel、PostCSS 和 ESLint)。它会在当前目录自动推导入口文件——入口能够是 main.js、index.js、App.vue 或 app.vue 中的一个。
注:在此项目中写 less 提示须要 css-loader
,编写的 postcss
也未生效 color: lch(53 105 40);
—— lch 是明天的 css 语法。
你也可使用 vue build
将目标文件构建成一个生产环境的包并用来部署:
demo> vue build / Building for production... File Size Gzipped dist\js\chunk-vendors.86166fc4.js 65.95 KiB 23.71 KiB dist\js\app.6d4e2596.js 1.79 KiB 0.89 KiB
dist
目录中会生成 index.html
,笔者在 dist 目录下运行静态文件服务器,在打开的页面中能看到 Hello!
:
demo> cd dist dist> anywhere Running at http://192.168.85.1:8000/ Also running at https://192.168.85.1:8001/
vue build
也提供了将组件构建成为一个库或一个 Web Components 组件的能力
运行如下命令来建立一个新项目:
> vue create vue-hello-world
提示选取一个预设(preset)。
Vue CLI v4.5.13 ? Please pick a preset: Default ([Vue 2] babel, eslint) // 默认选项 vue2 Default (Vue 3) ([Vue 3] babel, eslint) // 默认选项 vue3 > Manually select features // 手动选择
Tip:笔者使用 powershell 终端,能够经过上下键来切换选项
默认的设置很是适合快速建立一个新项目的原型,而手动设置则提供了更多的选项,它们是面向生产的项目更加须要的。
若是选择 default 则会直接建立项目,建立项目包括 babel,eslin 这些工具,而 vue-router,vuex等其余依赖须要本身手动安装。
因为咱们的项目须要 vue-router、vuex,因此就选择“手动选择”。
Vue CLI v4.5.13 ? Please pick a preset: Manually select features ? Check the features needed for your project: (*) Choose Vue version // vue 的版本 (*) Babel // 代码编译 (*) TypeScript // ts (*) Progressive Web App (PWA) Support // 渐进式网页应用程序 (*) Router // 路由 - vue router (*) Vuex // 状态管理 - vuex (*) CSS Pre-processors // css预处理 (*) Linter / Formatter // 代码风格、格式校验 (*) Unit Testing // 单元测试 >(*) E2E Testing // 端对端测试
Tip:这里为了演示,因此选择所有(笔者使用空格键来选中或取消)
所有选中后,回车,会依次询问咱们对应特性的一些具体需求,好比 vue 的版本、是否使用class风格的组件语法、路由是否使用 history 模式等等:
Vue CLI v4.5.13 ? Please pick a preset: Manually select features ? Check the features needed for your project: Choose Vue version, Babel, TS, PWA, Router, Vuex, CSS Pre-processors, Linter, Unit, E2E ? Choose a version of Vue.js that you want to start the project with (Use arrow keys) > 2.x 3.x
选择 vue 2,回车:
Vue CLI v4.5.13 ? Please pick a preset: Manually select features ? Check the features needed for your project: Choose Vue version, Babel, TS, PWA, Router, Vuex, CSS Pre-processors, Linter, Unit, E2E ? Choose a version of Vue.js that you want to start the project with 2.x ? Use class-style component syntax? (Y/n)
这里询问的是是否使用class风格的组件语法,若是在项目中想要保持使用TypeScript的class风格的话,建议你们选择 y:
... ? Choose a version of Vue.js that you want to start the project with 2.x ? Use class-style component syntax? Yes ? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? (Y/n)
将 Babel 与 TypeScript 一块儿使用,选择 y:
... ? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? Yes ? Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n)
路由是否使用 history 模式。由于 history 须要额外配置,因此这里选用 hash,输入n:
// CSS Pre-processors ... ? Use history mode for router? (Requires proper server setup for index fallback in production) No ? 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
选择一种CSS预处理类型,笔者选用 less:
// Linter / Formatter ... ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Less ? Pick a linter / formatter config: (Use arrow keys) > ESLint with error prevention only // 只进行报错提醒 ESLint + Airbnb config // airbnb 模式 ESLint + Standard config // 标准模式 ESLint + Prettier // prettier 模式 TSLint (deprecated) // 已弃用
选择 eslint 模式,笔者选标准模式:
... ? Pick a linter / formatter config: Standard ? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection) >(*) Lint on save ( ) Lint and fix on commit
选择校验时机,通常都会选择保存时校验,好及时作出调整,笔者选第一项:
// Unit Testing ... ? Pick additional lint features: Lint on save ? Pick a unit testing solution: (Use arrow keys) > Mocha + Chai Jes
选择单元测试解决方案,广泛用到最多的时Mocha + chai
,咱们也选第一项。
// E2E Testing E2E(End To End) ... ? Pick a unit testing solution: Mocha ? Pick an E2E testing solution: (Use arrow keys) > Cypress (Chrome only) Nightwatch (WebDriver-based) WebdriverIO (WebDriver/DevTools based)
选择端对端测试的类型,默认回车:
// 额外选项 ... ? Pick an E2E testing solution: Cypress ? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys) > In dedicated config files // 在专用配置文件中 In package.json
选择 Babel, ESLint 等配置存放位置,建议使用第一个(专用配置文件)
Tip: 若是选用第一项,例如 eslint 的配置就会单独存放在一个文件(.eslintrc.js)中;若是选第二项,该配置就会存放在 package.josn 中,而 package.json 是不能写注释,并且太多配置都写入 package.json 也很差维护
? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files ? Save this as a preset for future projects? (y/N)
是否保存成一个预设给之后项目使用。这里选 y,而后输入存储当前配置项的名称,例如 presetNameA
? Save this as a preset for future projects? Yes ? Save preset as:
随后就会建立完毕,并提示经过 npm run serve
启动服务:
... � Generating README.md... � Successfully created project vue-hello-world. � Get started with the following commands: $ cd vue-hello-world $ npm run serve
> npm run serve ... Time: 3055ms App running at: - Local: http://localhost:8080/ - Network: http://192.168.0.103:8080/
经过浏览器访问 http://localhost:8080/
便可访问项目。
Tip:下次建立项目的时候就会看到刚保存的预设(presetNameA):
> vue create demo Vue CLI v4.5.13 ? Please pick a preset: (Use arrow keys) > presetNameA ([Vue 2] less, babel, typescript, pwa, router, vuex, eslint, unit-mocha, e2e-cypress) Default ([Vue 2] babel, eslint) Default (Vue 3) ([Vue 3] babel, eslint) Manually select features
Vue CLI 使用了一套基于插件的架构。若是你查阅一个新建立项目的 package.json
,就会发现依赖都是以 @vue/cli-plugin-
开头的:
// vue-hello-world/package.json { "name": "vue-hello-world", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "test:unit": "vue-cli-service test:unit", "test:e2e": "vue-cli-service test:e2e", "lint": "vue-cli-service lint" }, "dependencies": { "core-js": "^3.6.5", "register-service-worker": "^1.7.1", "vue": "^2.6.11", "vue-class-component": "^7.2.3", "vue-property-decorator": "^9.1.2", "vue-router": "^3.2.0", "vuex": "^3.4.0" }, "devDependencies": { "@types/chai": "^4.2.11", "@types/mocha": "^5.2.4", "@typescript-eslint/eslint-plugin": "^4.18.0", "@typescript-eslint/parser": "^4.18.0", "@vue/cli-plugin-babel": "~4.5.0", "@vue/cli-plugin-e2e-cypress": "~4.5.0", "@vue/cli-plugin-eslint": "~4.5.0", "@vue/cli-plugin-pwa": "~4.5.0", "@vue/cli-plugin-router": "~4.5.0", "@vue/cli-plugin-typescript": "~4.5.0", "@vue/cli-plugin-unit-mocha": "~4.5.0", "@vue/cli-plugin-vuex": "~4.5.0", "@vue/cli-service": "~4.5.0", "@vue/eslint-config-standard": "^5.1.2", "@vue/eslint-config-typescript": "^7.0.0", "@vue/test-utils": "^1.0.3", "chai": "^4.1.2", "eslint": "^6.7.2", "eslint-plugin-import": "^2.20.2", "eslint-plugin-node": "^11.1.0", "eslint-plugin-promise": "^4.2.1", "eslint-plugin-standard": "^4.0.0", "eslint-plugin-vue": "^6.2.2", "less": "^3.0.4", "less-loader": "^5.0.0", "typescript": "~4.1.5", "vue-template-compiler": "^2.6.11" } }
插件能够修改 webpack 的内部配置,也能够向 vue-cli-service
注入命令。在项目建立的过程当中,绝大部分列出的特性都是经过插件来实现的。
基于插件的架构使得 Vue CLI 灵活且可扩展。
下面咱们将经过一个示例来说解插件,首先新建项目 demo2(选择 Default
):
// 选则`Default ([Vue 2] babel, eslint)`默认建立 > vue create demo2
Tip: 前面建立的项目(vue-hello-world
)是基于 typescript,演示起来不是很方便
每一个 CLI 插件都会包含一个 (用来建立文件的) 生成器和一个 (用来调整 webpack 核心配置和注入命令的) 运行时插件。当你使用 vue create
来建立一个新项目的时候,有些插件会根据你选择的特性被预安装好。若是你想在一个已经被建立好的项目中安装一个插件,可使用 vue add 命令,例如 vue add axios
Tip:vue add
的设计意图是为了安装和调用 Vue CLI 插件。这不意味着替换掉普通的 npm 包。对于这些普通的 npm 包,你仍然须要选用包管理器。
下面咱们经过安装 axios 来详细了解一下vue add 插件
和 npm install 包
之间的区别:
> npm i axios
安装完成,项目中只有 package.json 会增长相应的依赖:
"dependencies": { + "axios": "^0.21.1", "core-js": "^3.6.5", "vue": "^2.6.11" },
将 axios 这个包删除,再次用 vue add
安装 axios 插件:
// 删除 > npm r axios
> vue add axios WARN There are uncommitted changes in the current repository, it's recommended to commit or stash them first. ? Still proceed?
Tip: 因为会更改文件,因此会让你先提交代码
> vue add axios � Installing vue-cli-plugin-axios... ... Run `npm audit` for details. ✔ Successfully installed plugin: vue-cli-plugin-axios
告诉咱们正在安装的包是:vue-cli-plugin-axios
安装完成,经过 git status
就能知道此命令修改的文件和内容:
demo2> git status On branch master Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: package-lock.json modified: package.json modified: src/main.js Untracked files: (use "git add <file>..." to include in what will be committed) src/plugins/
// package.json "devDependencies": { "axios": "^0.18.0", "vue-cli-plugin-axios": "~0.0.4", },
// main.js import './plugins/axios'
// src/plugins/axios.js "use strict"; import Vue from 'vue'; import axios from "axios"; // Full config: https://github.com/axios/axios#request-config // axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || ''; // axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; let config = { // baseURL: process.env.baseURL || process.env.apiUrl || "" // timeout: 60 * 1000, // Timeout // withCredentials: true, // Check cross-site Access-Control }; const _axios = axios.create(config); _axios.interceptors.request.use( function(config) { // Do something before request is sent return config; }, function(error) { // Do something with request error return Promise.reject(error); } ); // Add a response interceptor _axios.interceptors.response.use( function(response) { // Do something with response data return response; }, function(error) { // Do something with response error return Promise.reject(error); } ); Plugin.install = function(Vue, options) { Vue.axios = _axios; window.axios = _axios; Object.defineProperties(Vue.prototype, { axios: { get() { return _axios; } }, $axios: { get() { return _axios; } }, }); }; Vue.use(Plugin) export default Plugin;
接着启动服务,eslint 报错,因而修改 eslint 配置绕过代码校验,再次重启服务。
// package.json "extends": [ "plugin:vue/essential", - "eslint:recommended" ],
在任意组件中便可使用 axios,例如在 App.vue 中使用:
<script> export default {} console.log(window.axios); </script>
浏览器控制台会输出:
ƒ wrap() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } return fn.apply(thisArg, args); }
至此,axios 已经成功引入咱们的项目,并且范文也已经就绪。
经过这个示例咱们也就明白,vue 提供的这个插件比 npm 这种方式更友好,好比有范文。
> vue add vuex � Installing @vue/cli-plugin-vuex... ...
安装 axios 对应的包是 vue-cli-plugin-axios
,以 vue-cli-plugin-
开头,属于第三方插件
而 vuex 对应的包是 @vue/cli-plugin-vuex
,以 @vue/cli-plugin-
开头。
咱们经过 vue ui
命令使用 GUI 安装和管理插件。因为前面咱们已经全局安装,因此在任意目录下运行便可:
> vue ui � Starting GUI... � Ready on http://localhost:8001
浏览器自动打开页面,并来到Vue 项目管理器
系统,导入项目(例如 vue-hello-world
),你会能够看见以下几个菜单:
添加插件
就能够查找插件,在查找插件的页面,咱们知道:
jquery
对应的插件axios
对应的插件,将鼠标移到添加插件的图标上会显示:这个插件带有一个生成器,能够在项目中修改或增长文件vue
),开发依赖有哪些(例如 eslint
)配置 Vue 项目
、代码质量和纠错
等serve
、build
、lint
等)。还有 inspect
,能检查 webpack 配置,好比查看项目对应开发环境和生成环境的 webpack
配置。一个 Vue CLI preset 是一个包含建立新项目所需预约义选项和插件的 JSON 对象,让用户无需在命令提示中选择它们。
在 vue create
过程当中保存的 preset 会被放在你的 home 目录下的一个配置文件中 (~/.vuerc
)。你能够经过直接编辑这个文件来调整、添加、删除保存好的 preset。
笔者预设以下:
> cat ~/.vuerc { "useTaobaoRegistry": false, "latestVersion": "4.5.13", "lastChecked": 1622962273301, "presets": { "presetNameA": { "useConfigFiles": true, "plugins": { "@vue/cli-plugin-babel": {}, "@vue/cli-plugin-typescript": { "classComponent": true, "useTsWithBabel": true }, "@vue/cli-plugin-pwa": {}, "@vue/cli-plugin-router": { "historyMode": false }, "@vue/cli-plugin-vuex": {}, "@vue/cli-plugin-eslint": { "config": "standard", "lintOn": [ "save" ] }, "@vue/cli-plugin-unit-mocha": {}, "@vue/cli-plugin-e2e-cypress": {} }, "vueVersion": "2", "cssPreprocessor": "less" } } }
Preset 的数据会被插件生成器用来生成相应的项目文件。除了上述这些字段,你也能够为集成工具添加配置:
{ "useConfigFiles": true, "plugins": {...}, "configs": { "vue": {...}, "postcss": {...}, "eslintConfig": {...}, "jest": {...} } }
这些额外的配置将会根据 useConfigFiles
的值被合并到 package.json
或相应的配置文件中。例如,当 "useConfigFiles": true
的时候,configs
的值将会被合并到 vue.config.js
中。
你能够显式地指定用到的插件的版本:
{ "plugins": { "@vue/cli-plugin-eslint": { "version": "^3.0.0", // ... 该插件的其它选项 } } }
注意对于官方插件来讲这不是必须的——当被忽略时,CLI 会自动使用 registry 中最新的版本。不过推荐为 preset 列出的全部第三方插件提供显式的版本范围。
在一个 Vue CLI 项目中,@vue/cli-service
安装了一个名为 vue-cli-service 的命令。你能够在 npm scripts
中以 vue-cli-service
、或者从终端中以 ./node_modules/.bin/vue-cli-service
访问这个命令。
上文咱们建立的项目 demo2 的 package.json
中的命令有:
{ "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint" } }
能够经过 npm
或 npx
(最新版的 npm 应该已经自带) 执行命令:
> npm run serve
> npx vue-cli-service serve
Tip: 能够经过 vue ui
命令使用 GUI 运行更多的特性脚本
用法:vue-cli-service serve [options] [entry] 选项: --open 在服务器启动时打开浏览器 --copy 在服务器启动时将 URL 复制到剪切版 --mode 指定环境模式 (默认值:development) --host 指定 host (默认值:0.0.0.0) --port 指定 port (默认值:8080) --https 使用 https (默认值:false)
vue-cli-service serve
命令会启动一个开发服务器 (基于 webpack-dev-server) 并附带开箱即用的模块热重载 (Hot-Module-Replacement)。
除了经过命令行参数,你也可使用 vue.config.js 里的 devServer 字段配置开发服务器
命令行参数 [entry] 将被指定为惟一入口,而非额外的追加入口。尝试使用 [entry] 覆盖 config.pages 中的 entry 将可能引起错误。
// 在服务器启动时打开浏览器 demo2> npx vue-cli-service serve --open // 或者指定 entry demo2> npx vue-cli-service serve --open ./src/main.js
Tip:终端可能由于 eslint 报错而终止编译,能够更改 eslint 配置。在项目根目录下新建 vue.config.js
,重启服务便可。
// vue.config.js module.exports = { lintOnSave: true }
用法:vue-cli-service build [options] [entry|pattern] 选项: --mode 指定环境模式 (默认值:production) --dest 指定输出目录 (默认值:dist) --modern 面向现代浏览器带自动回退地构建应用 --target app | lib | wc | wc-async (默认值:app) --name 库或 Web Components 模式下的名字 (默认值:package.json 中的 "name" 字段或入口文件名) --no-clean 在构建项目以前不清除目标目录 --report 生成 report.html 以帮助分析包内容 --report-json 生成 report.json 以帮助分析包内容 --watch 监听文件变化
vue-cli-service build
会在 dist/
目录产生一个可用于生产环境的包,带有 JS/CSS/HTML
的压缩,和为更好的缓存而作的自动的 vendor chunk splitting。它的 chunk manifest 会内联在 HTML 里。
这里还有一些有用的命令参数:
--modern
使用现代模式构建应用,为现代浏览器交付原生支持的 ES2015 代码,并生成一个兼容老浏览器的包用来自动回退。// 打包生成了两份:现代包和遗留包 demo2> npx vue-cli-service build --modern // 为生产构建遗留包... / Building legacy bundle for production... File Size Gzipped dist\js\chunk-vendors-legacy.7b12297e.js 117.56 KiB 40.92 KiB dist\js\app-legacy.853ea99d.js 5.15 KiB 1.84 KiB dist\css\app.fb0c6e1c.css 0.33 KiB 0.23 KiB // 省略了图像和其余类型的资产 Images and other types of assets omitted. // 为生产构建现代捆绑... - Building modern bundle for production... File Size Gzipped dist\js\chunk-vendors.1e2bb21b.js 92.78 KiB 32.14 KiB dist\js\app.d739a095.js 5.07 KiB 1.81 KiB dist\css\app.fb0c6e1c.css 0.33 KiB 0.23 KiB // 省略了图像和其余类型的资产 Images and other types of assets omitted.
--target
容许你将项目中的任何组件以一个库或 Web Components 组件的方式进行构建。
--report
和 --report-json
会根据构建统计生成报告,它会帮助你分析包中包含的模块们的大小。
demo2> npx vue-cli-service build --report | Building for production... File Size Gzipped dist\js\chunk-vendors.7b12297e.js 117.55 KiB 40.92 KiB dist\js\app.853ea99d.js 5.14 KiB 1.83 KiB dist\css\app.fb0c6e1c.css 0.33 KiB 0.23 KiB Images and other types of assets omitted.
会在 dist 目录中生成 report.html
。
Tip: 若是你使用的是 vscode,只须要安装 Live Server 插件,便可右键经过 live server 查看 report.html
,很是方便。
若是是 --report
,则不会生成 report.html
,而会生成 report.json
。
用法:vue-cli-service inspect [options] [...paths] 选项: --mode 指定环境模式 (默认值:development)
审查一个 Vue CLI 项目的 webpack config
。请看示例:
// 提取出webpack开发配置,导出到 webpack.config.development.js 中 demo2> npx vue-cli-service inspect --mode development >> webpack.config.development.js // 提取出webpack生成配置 demo2> npx vue-cli-service inspect --mode production >> webpack.config.production.js
注:接下来咱们学习过程当中会参考这两个配置文件
有些 CLI 插件会向 vue-cli-service 注入额外的命令。例如 @vue/cli-plugin-eslint 会注入 vue-cli-service lint
命令。你能够运行如下命令查看全部注入的命令:
demo2> npx vue-cli-service help Usage: vue-cli-service <command> [options] Commands: serve start development server build build for production inspect inspect internal webpack config lint lint and fix source files run vue-cli-service help [command] for usage of a specific command.
也能够这样学习每一个命令可用的选项:
npx vue-cli-service help [command]
cache-loader
会默认为 Vue/Babel/TypeScript 编译开启。文件会缓存在 node_modules/.cache
中——若是你遇到了编译方面的问题,记得先删掉缓存目录以后再试试看。// demo2 中的缓存文件: demo2> dir .\node_modules\.cache\ Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2021/8/11 11:30 babel-loader d----- 2021/8/11 11:30 eslint-loader d----- 2021/7/19 19:31 terser-webpack-plugin d----- 2021/8/11 11:30 vue-loader
Tip:虽然 package.json 中没有 cache-loader
和 thread-loader
,但 demo2/node_modules 中有。
在安装以后,@vue/cli-service 也会安装 yorkie,它会让你在 package.json 的 gitHooks 字段中方便地指定 Git hook:
{ "gitHooks": { "pre-commit": "lint-staged" }, "lint-staged": { "*.{js,vue}": [ "vue-cli-service lint", "git add" ] } }
Tip:yorkie,fork 项目 husky,并作了一些改变,好比更改了从 package.json 中读取钩子的位置:
// before { "scripts": { "precommit": "foo" } }
// after { "gitHooks": { "pre-commit": "foo" } }
具体用法,请看示例(在demo2基础上进行):
// package.json { ... "gitHooks": { "pre-commit": "lint-staged" }, "lint-staged": { "*.{js,vue}": [ "vue-cli-service lint", "git add" ] } }
执行 git commit
命令报错:
demo2> git commit -m 'xx' On branch master (use "git add <file>..." to include in what will be committed) src/a.js 'lint-staged' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 pre-commit hook failed (add --no-verify to bypass)
安装依赖包:
// lint-staged - 对暂存的 git 文件运行 linter,不要让很差的代码溜进你的代码库! demo2> npm i -D lint-staged
接下来给 eslint 增长一个规则,而后在 a.js 中故意不遵照该规则:
// package.json { "eslintConfig": { "rules": { "no-console": "error" } }, }
// src/a.js let i = 1 console.log(i);
执行git commit
命令,验证不经过,终止提交:
// 须要先 git add demo2> git add src/a.js demo2> git commit -m 'xx' > running pre-commit hook: lint-staged ⚠ Some of your tasks use `git add` command. Please remove it from the config since all modifications made by tasks will be automatically added to the git commit index. [STARTED] Preparing... [SUCCESS] Preparing... [STARTED] Running tasks... [STARTED] Running tasks for *.{js,vue} [STARTED] vue-cli-service lint [FAILED] vue-cli-service lint [FAILED] [FAILED] vue-cli-service lint [FAILED] [SUCCESS] Running tasks... [STARTED] Applying modifications... [SKIPPED] Skipped because of errors from tasks. [STARTED] Reverting to original state because of errors... [SUCCESS] Reverting to original state because of errors... [STARTED] Cleaning up... [SUCCESS] Cleaning up... ✖ vue-cli-service lint: error: Unexpected console statement (no-console) at src\a.js:2:1: 1 | let i = 1 > 2 | console.log(i); | ^ 3 | 1 error found. pre-commit hook failed (add --no-verify to bypass)
Tip:Git 钩子,和其它版本控制系统同样,Git 能在特定的重要动做发生时触发自定义脚本。有两组这样的钩子:客户端的和服务器端的。客户端钩子由诸如提交和合并这样的操做所调用,而服务器端钩子做用于诸如接收被推送的提交这样的联网操做。你能够为所欲为地运用这些钩子。
// 项目 demo2 的 git hooks demo2> dir .\.git\hooks\ 目录: demo2\.git\hooks Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2021/7/19 9:11 870 applypatch-msg -a---- 2021/7/19 9:07 478 applypatch-msg.sample -a---- 2021/7/19 9:11 854 commit-msg -a---- 2021/7/19 9:07 896 commit-msg.sample -a---- 2021/7/19 9:07 4655 fsmonitor-watchman.sample -a---- 2021/7/19 9:11 874 post-applypatch -a---- 2021/7/19 9:11 866 post-checkout -a---- 2021/7/19 9:11 858 post-commit -a---- 2021/7/19 9:11 854 post-merge -a---- 2021/7/19 9:11 862 post-receive -a---- 2021/7/19 9:11 862 post-rewrite -a---- 2021/7/19 9:11 858 post-update -a---- 2021/7/19 9:07 189 post-update.sample -a---- 2021/7/19 9:11 870 pre-applypatch -a---- 2021/7/19 9:07 424 pre-applypatch.sample -a---- 2021/7/19 9:11 858 pre-auto-gc -a---- 2021/7/19 9:11 854 pre-commit -a---- 2021/7/19 9:07 1643 pre-commit.sample -a---- 2021/7/19 9:07 416 pre-merge-commit.sample -a---- 2021/7/19 9:11 846 pre-push -a---- 2021/7/19 9:07 1348 pre-push.sample -a---- 2021/7/19 9:11 854 pre-rebase -a---- 2021/7/19 9:07 4898 pre-rebase.sample -a---- 2021/7/19 9:11 858 pre-receive -a---- 2021/7/19 9:07 544 pre-receive.sample -a---- 2021/7/19 9:11 913 prepare-commit-msg -a---- 2021/7/19 9:07 1492 prepare-commit-msg.sample -a---- 2021/7/19 9:11 878 push-to-checkout -a---- 2021/7/19 9:11 886 sendemail-validate -a---- 2021/7/19 9:11 838 update -a---- 2021/7/19 9:07 3635 update.sample
经过 vue create 建立的项目无需额外的配置就已经能够跑起来了。插件的设计也是能够相互共存的,因此绝大多数状况下,你只须要在交互式命令提示中选取须要的功能便可。
不过咱们也知道知足每个需求是不太可能的,并且一个项目的需求也会不断改变。经过 Vue CLI 建立的项目让你无需 eject 就可以配置工具的几乎每一个角落。
其余章节请看: