Vue CLI 是一个基于 Vue.js 进行快速开发的完整系统,能够帮助开发者快速搭建应用,提供了默认的开发环境相关配置,也提供了配置文件用于开发者根据自己需求灵活调整配置。
安装
全局安装 @vue/cli:
$ npm i @vue/cli -g
安装后,可运行查看:
$ vue --version
创建项目
GUI 方式创建
$ vue ui
命令行方式创建
在命令行中运行:
$ vue create
如:
$ vue create vue-cli-demo
执行后会显示选择创建项目特性的向导
手动选择项目中使用到的特性:
? Please pick a preset:
vue-router ([Vue 2] node-sass, babel, router, eslint)
Default ([Vue 2] babel, eslint)
Default (Vue 3 Preview) ([Vue 3] babel, eslint)
Manually select features
选择特性:
? Check the features needed for your project: (Press to select, to toggle all, to invert selection)
() Choose Vue version
() Babel # 这是一个 JS 转译的工具
( ) TypeScript
( ) Progressive Web App (PWA) Support
() Router
() Vuex
() CSS Pre-processors # CSS 预处理器,如 sass、less
() Linter / Formatter # 保障代码规范的工具,如 ESLint
( ) Unit Testing
( ) E2E Testing
选择 Vue 版本:
? Choose a version of Vue.js that you want to start the project with (Use arrow keys)
2.x
3.x (Preview)
选择 CSS 预处理器:
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default):
Sass/SCSS (with dart-sass)
Sass/SCSS (with node-sass)
Less
Stylus
选择 linter/formater 规范:
? Pick a linter / formatter config:
ESLint with error prevention only
ESLint + Airbnb config
ESLint + Standard config
ESLint + Prettier
linter 工具校验时机及错误处理:
? Pick additional lint features: (Press to select, to toggle all, to invert selection)
(*) Lint on save
( ) Lint and fix on commit
选择保存相关配置文件的位置:
? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
In dedicated config files # 独立的配置文件
In package.json
是否预存以上的选择:
? Save this as a preset for future projects? (y/N) n
创建项目并安装依赖
进行项目目录,运行项目
$ cd
如:
$ cd vue-cli-demo
$ npm run serve # 运行开发环境任务
访问:
DONE Compiled successfully in 10681ms 10:05:33
App running at:
- Local: http://localhost:8080/
- Network: http://10.7.161.92:8080/
Note that the development build is not optimized.
To create a production build, run npm run build.
注意,如果选择 node-sass 后,在安装时报错,可以切换 node-sass 包的源(建议使用 dart-sass):
$ npm config set sass_binary_site http://cdn.npm.taobao.org/dist/node-sass
在 vs-code 中可以安装 ESLint 扩展程序,在设置中添加如下代码片段,即可实现保存时根据 ESLint 的配置自动格式化代码:
“editor.codeActionsOnSave”: {
“source.fixAll.eslint”: true
},
项目目录结构
public – 静态资源(入口HTML文件与 favicon 图标)
src – 源代码目录(开发者在开发过程中所写的源码)
|-- assets: 放置应用中使用到的静态媒体资源,如图像、音视频文件等
|-- components: 放置应用中可以被复用的组件
|-- App.vue:App组件,是一个单文件组件
|-- main.js:应用的入口JS文件
.eslintrc.js – 这是 ESLint 工具的配置文件
babel.config.js – 这是 Babel 工具的配置文件
package.json – 项目的配置文件
package.json 中的 scripts:
{
“scripts”: {
“serve”: “vue-cli-service serve”, // 开发环境下的任务
“build”: “vue-cli-service build”, // 构建生产环境的任务
“lint”: “vue-cli-service lint” // 代码格式化任务
},
}