Vue-Cli 是 vue 专用起步工具,用 Vue-Cli 起步能够:
① 项目直接安装了Vue、Vue-Routre、ESLint等常用依赖
② webpack已经配置好了,webpack-dev-server已经集成了
③ 一些配置好的 git
一、配置起步环境
全局安装 @vue/cli
npm install -g @vue/cli
初始化一个项目:
vue create my_project
问你是否使用更快的淘宝镜像,我选择 No.
C:\Users\Administrator\Desktop>vue create my_project
? Your connection to the default npm registry seems to be slow.
Use https://registry.npm.taobao.org for faster installation? No
使用 Vue create 创建项目是使用默认配置(包含babel, eslint)还是手动选择。
Vue CLI v3.11.0
? Please pick a preset: (Use arrow keys)
> default (babel, eslint)
Manually select features
使用默认配置的话可以直接回车。
Vue CLI v3.11.0
✨ Creating project in C:\Users\Administrator\Desktop\my_project.
� Initializing git repository...
⚙ Installing CLI plugins. This might take a while...
[ .................] / fetchMetadata: sill pacote range manifest for @vue/cli-p
然后自动安装依赖,其实就是自动在创建的项目目录下进行npm install
了,如果嫌慢的话可以 ctrl+c
打断,然后使用 cnpm install
。
如果不选则默认来看看手动选择的情况。进入之后可手动选择一些特性
- Babel 编译作用
- TypeScript 强类型的 JS
- Progressive Web App (PWA) Support 渐进式 APP ,主要用于兼容移动端
- router Vue 路由
- Vuex Vue的状态管理器
- CSS 预处理器,可选择使用 less 、sass、 stylus等预处理器
- Linter / Formatter 代码检测和格式化
- Unit Testing 单元测试
- 还有暂时不考虑端到端测试(E2E Testing)
Vue CLI v3.11.0
? Please pick a preset: Manually select features
? Check the features needed for your project: (Press <space> to select, <a> to t
oggle all, <i> to invert selection)
>(*) Babel
( ) TypeScript
( ) Progressive Web App (PWA) Support
(*) Router
(*) Vuex
(*) CSS Pre-processors
(*) Linter / Formatter
( ) Unit Testing
( ) E2E Testing
它就会让你选一些特性。括号前面加上星号说明选中没加,就没选中。上下键控制上下,空格进行确定/取消,a 全选。i 反选。
以上按自己需要的选择好,我选择了常用的五个,回车:
询问路由方式是否使用 history 模式。一般都是单页面开发不选择 history ,选择 hashhistory 所以这里输入 N 会表示 进入 hash 模式。
? Use history mode for router? (Requires proper server setup for index fallback
in production) (Y/n)
继续回车:
选择 样式表 CSS 的预处理器:一般我使用 less ,按自己项目要求选择。
? 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
继续回车:
接下来进行 ESLint 代码规范等级配置( 选择标准 ESLint + Standard config)标准配置:
? Pick a linter / formatter config: (Use arrow keys)
> ESLint with error prevention only
ESLint + Airbnb config
ESLint + Standard config
ESLint + Prettier
选择何时进行代码校验,此处选择在保存时进行检测:
>(*) Lint on save//保存及检测
( ) Lint and fix on commit
选择 Babel、PostCSS、ESLint等配置文件存放位置,此处选择单独保存在各自的配置文件中。
? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? (Use arro
w keys)
> In dedicated config files
In package.json
在未来的项目中使用:
Save this as a preset for future projects? (y/N)N
//输入 N 直接自动跳转
//选择 Y 会多一步
Save preset as:? Save preset as: 我的标准配置项目
//保存本次配置名字为`我的标准配置项目`,下次进行项目重建,会多个此次保存的配置名。
? Please pick a preset:
> 我的标准配置项目 (vue-router, vuex, less, babel, eslint)
default (babel, eslint)
Manually select features
至此命令行敲击完成,等项目初始化完成,下面的安装完成。
Vue CLI v3.11.0
✨ Creating project in C:\Users\Administrator\Desktop\my_project.
� Initializing git repository...
⚙ Installing CLI plugins. This might take a while...
[ .................] | fetchMetadata: sill pacote range manifest for once@^1.3.
装的时候可能会报错,请使用npm cache clean -f
来清除一下缓存。再进行重装。
Vue CLI v3.11.0
✨ Creating project in C:\Users\Administrator\Desktop\my_peoject.
� Initializing git repository...
⚙ Installing CLI plugins. This might take a while...
npm ERR! Unexpected end of JSON input while parsing near '..."@vue/cli-overlay":
"^'
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\Administrator\AppData\Roaming\npm-cache\_logs\2019-09-11T0
1_04_28_478Z-debug.log
ERROR command failed: npm install --loglevel error
自动进入npm install
时代。还是那句话嫌慢可以打断,使用 cnpm 装。
项目运行起步命令:
npm run serve
访问 :http://127.0.0.1:8080/
查看效果
二、 ESLint 使用介绍
ESLint 使用 Espree 解析 JavaScript。ESLint 使用 AST 去分析代码中的模式ESLint 是完全插件化的。每一个规则都是一个插件并且你可以在运行时添加更多的规则。
我们现在的环境已经集成所以不需要使用npm install eslint --save-dev
安装了。
举例看下配置规则:
{
"rules": {
"semi": ["error", "always"],
"quotes": ["error", "double"]
}
}
"semi"
(分号) 和 "quotes"
(引号)是 ESLint 中 规则 的名称。数组里面第一个值表示错误级别,可以使下面的值之一:
-
"off"
or 0 - 关闭规则 -
"warn"
or 1 - 将规则视为一个警告(不会影响退出码) -
"error"
or 2 - 将规则视为一个错误 (退出码为1)
看一下在项目中的应用,在项目目录打开 package.json 文件找到:
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"rules": {},//配置规则的地方
"parserOptions": {
"parser": "babel-eslint"
}
},
看着官网进行配置:http://eslint.cn/docs/user-guide/configuring。
我只配置四条规则:
"rules": {
"indent": ["error", "tab"],
"quotes": ["error", "double"],
"semi": ["error", "always"],
"key-spacing": [2, {
"beforeColon": false,
"afterColon": true
}]
},
//缩进一个tab
//采用双引号
//语句结尾必须有分号
// 禁止在对象字面量的键和冒号之间存在空格;要求在对象字面量的冒号和值之间存在至少有一个空格
当不改变任何文件的情况下直接npm run serve
运行文件,Eslint 开始起作用,文件报错。随机选取一个错误:
error: Missing semicolon (semi) at src\main.js:8:18:
6 | new Vue({
7 | render: h => h(App),
> 8 | }).$mount('#app')
| ^
9 |
上面是 CMD 窗口出现的错误,现在更改一下 webpack 的配置,让 eslint 的错误在屏幕上显示。在和 package.json 同级目录下,创建 vue.config.js 文件。
配置内容参考链接:
https://cli.vuejs.org/zh/config/#lintonsave
vue.config.js是一个可选的配置文件,如果项目的(和package.json同级的)根目录中存在这个文件,那么它会被@vue/cli自动加载
链接内容为:
依图复制以下代码放入 vue.config.js:
module.exports = {
"devServer": {
overlay: {
warnings: true,
errors: true
}
}
};
此处就是平时手动配置的 webpack.config.js 。我们还可以配置端口号:
port: 8100
自定义 端口号,以及代理跨域等等。甚至可以直接webpack-dev-server --content-base ./public --port 8080
命令行启动程序。
然后重新运行就发现错误上屏幕了,如下:
三、介绍目录文件
项目结构注解:
┣✈ .git :git的配置文件
┣✈ .gitignore:配置 git 提交时忽略提交的文件
┣✈ node-modules:依赖的 node 库文件
┣✈ public:公共文件,如 index.html 文件和 style 样式文件
┗✈ src
┣✈ assets:资源文件img、css、html等等
┣✈ component:自己写的组件
┣✈ views 视图布局页面组件
┣✈ App.vue:vue 的根组件
┣✈ main.js:主函数入口文件
┣✈ router.js 路由文件
┣✈ store.js vuex的配置文件
┣✈ package.json:项目依赖文件
┣✈ README.md:一些常用命令介绍
┣✈ .browserslistrc:项目的目标浏览器的范围
┣✈ .editorconfig:代码编辑器配置
┣✈ .eslintrc.js:eslint配置文件,代码校验规则就是在这里
┣✈ babel.config.js:翻译;使用一些预设
┣✈ package-lock.json:版本管理使用的文件
┣✈ postcss.config.js:配置css规则的
-
.gitignore
注意.gitignore
文件表示git
忽略的文件,一般来讲node_modules
是要被忽略,不会被git
托管的。 -
.browserslistrc
:browserslist -
eslintrc.js
:配置文件详解 eslintrc.js
module.exports = {
root: true,// 标识当前配置文件为eslint的根配置文件,让其停止在父级目录中继续寻找。
// 运行环境
env: {
node: true// Node.js 全局变量和 Node.js 作用域。
},
//规则继承
//eslint内置推荐规则,就只有一个,即「eslint:recommended」
'extends': [
//vue 自己额外添加的规则,例如 v-if, v-else 等指令检测
'plugin:vue/essential',// 额外添加的规则可查看 https://vuejs.github.io/eslint-plugin-vue/rules/
'@vue/standard'
],
// 自定义规则
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
},
parserOptions: {
// 解析器ESLint 默认使用Espree作为其解析器
parser: 'babel-eslint'
}
}
-
.editorconfig
:https://www.cnblogs.com/xieqian/p/10045610.html
看一下main.js
顺便加一下注释并修改符合 ESLint 规则。
import Vue from "vue";
import App from "./App.vue";
// 设置为 false 以阻止 vue 在启动时生成生产提示。
Vue.config.productionTip = false;
// $mount和el写法一样都是挂载点
new Vue({
render: h => h(App),
}).$mount("#app");
四、默认安装配置 vuex 和 iview。
安装插件:
npm install --save-dev iview
npm install --save-dev vuex
配置 iview 我们还是的找到 node_modules\iview\dist 文件里面的 styles 样式文件,放到我们项目目录 public 里面,在 index.html 里面引入。
<link rel="stylesheet" href="<%= BASE_URL %>styles/iview.css">
稍微有点不一样,注意下的加"<%= BASE_URL %>
后面在放地址,地址不能./
,文件自动补,加了就多了。例如文件自动带的 favicon.ico <link rel="icon" href="<%= BASE_URL %>favicon.ico">
<=源代码。渲染后=> <link rel="icon" href="/favicon.ico">
所以你也可以认为"<%= BASE_URL %>"
就是补个斜杠。
为什么这么写?
参考:HTML 和静态资源 | Vue CLI https://cli.vuejs.org/zh/guide/html-and-static-assets.html#html
public/index.html
文件是一个会被 html-webpack-plugin 处理的模板。在构建过程中,资源链接会被自动注入。因为 index 文件被用作模板,所以你可以使用 lodash template 语法插入内容。
完成后,重新运行npm run serve
。
改变配置 main.js 如下:
import Vue from "vue";
import App from "./App.vue";
import Vuex from "vuex";
import iview from "iview";
import store from "./vuex";
// 设置为 false 以阻止 vue 在启动时生成生产提示。
Vue.config.productionTip = false;
Vue.use(iview);
Vue.use(Vuex);
// $mount和el写法一样都是挂载点
new Vue({
render: h => h(App),
store: new Vuex.Store(store),
}).$mount("#app");
需要注意的是:
现在的 webpack 比较强大,所有文件的后缀名都不需要写了!而且文件里面所有的 index 文件会自动加载。
App.vue 主逻辑测试代码:
<template>
<div>
<!-- 放入一个日历测试iview插件是否成功 -->
<DatePicker/>
<!-- 加法器 -->
<h1>{{$store.state.couterStore.a}}</h1>
<Button @click="$store.commit('couterStore/ADD')">按我加一</Button>
</div>
</template>
<script>
export default {
};
</script>
<style scoped>
</style>
vuex 代码状态管理容器:
/couterStore.js
export default {
namespaced: true,
state: {
a: 10,
},
mutations: {
ADD(state){
state.a++;
},
},
actions: {
}
};
//index.js
import couterStore from "./couterStore";
export default {
modules: {
couterStore,
}
};
打开http://127.0.0.1:8080/
查看效果:
2019年12月22日16:21:08补充:
现在 Vue-cli 乱搞,你 Cli 起步完成之后,默认带 ESlint,带就带了,关键它不让你使用 console,有些东西不利于开发调试。这不扯淡吗。具体看看不让我们干啥了。
error: Unexpected console statement (no-console) at//不允许console
error: Mixed spaces and tabs (no-mixed-spaces-and-tabs) at//空格与缩进不能混用
error: 'progressEvent' is defined but never used (no-unused-vars) at
//不能有声明后未被使用的变量或参数
error: 'Qs' is not defined (no-undef) at//不能有未定义的变量
我主要是测试了这几条,解决重要是这样解决的:rules 必须是严格的 JSON 格式
"rules": {
"no-console": 0,
"no-mixed-spaces-and-tabs": [0, false],
"no-unused-vars": [0, {"vars": "all", "args": "after-used"}],
"no-undef": 0
},
如果还有报错可参考如下的 ES-Lint 配置:
"no-alert": 0,//禁止使用alert confirm prompt
"no-array-constructor": 2,//禁止使用数组构造器
"no-bitwise": 0,//禁止使用按位运算符
"no-caller": 1,//禁止使用arguments.caller或arguments.callee
"no-catch-shadow": 2,//禁止catch子句参数与外部作用域变量同名
"no-class-assign": 2,//禁止给类赋值
"no-cond-assign": 2,//禁止在条件表达式中使用赋值语句
"no-console": 2,//禁止使用console
"no-const-assign": 2,//禁止修改const声明的变量
"no-constant-condition": 2,//禁止在条件中使用常量表达式 if(true) if(1)
"no-continue": 0,//禁止使用continue
"no-control-regex": 2,//禁止在正则表达式中使用控制字符
"no-debugger": 2,//禁止使用debugger
"no-delete-var": 2,//不能对var声明的变量使用delete操作符
"no-div-regex": 1,//不能使用看起来像除法的正则表达式/=foo/
"no-dupe-keys": 2,//在创建对象字面量时不允许键重复 {a:1,a:1}
"no-dupe-args": 2,//函数参数不能重复
"no-duplicate-case": 2,//switch中的case标签不能重复
"no-else-return": 2,//如果if语句里面有return,后面不能跟else语句
"no-empty": 2,//块语句中的内容不能为空
"no-empty-character-class": 2,//正则表达式中的[]内容不能为空
"no-empty-label": 2,//禁止使用空label
"no-eq-null": 2,//禁止对null使用==或!=运算符
"no-eval": 1,//禁止使用eval
"no-ex-assign": 2,//禁止给catch语句中的异常参数赋值
"no-extend-native": 2,//禁止扩展native对象
"no-extra-bind": 2,//禁止不必要的函数绑定
"no-extra-boolean-cast": 2,//禁止不必要的bool转换
"no-extra-parens": 2,//禁止非必要的括号
"no-extra-semi": 2,//禁止多余的冒号
"no-fallthrough": 1,//禁止switch穿透
"no-floating-decimal": 2,//禁止省略浮点数中的0 .5 3.
"no-func-assign": 2,//禁止重复的函数声明
"no-implicit-coercion": 1,//禁止隐式转换
"no-implied-eval": 2,//禁止使用隐式eval
"no-inline-comments": 0,//禁止行内备注
"no-inner-declarations": [2, "functions"],//禁止在块语句中使用声明(变量或函数)
"no-invalid-regexp": 2,//禁止无效的正则表达式
"no-invalid-this": 2,//禁止无效的this,只能用在构造器,类,对象字面量
"no-irregular-whitespace": 2,//不能有不规则的空格
"no-iterator": 2,//禁止使用__iterator__ 属性
"no-label-var": 2,//label名不能与var声明的变量名相同
"no-labels": 2,//禁止标签声明
"no-lone-blocks": 2,//禁止不必要的嵌套块
"no-lonely-if": 2,//禁止else语句内只有if语句
"no-loop-func": 1,//禁止在循环中使用函数(如果没有引用外部变量不形成闭包就可以)
"no-mixed-requires": [0, false],//声明时不能混用声明类型
"no-mixed-spaces-and-tabs": [2, false],//禁止混用tab和空格
"linebreak-style": [0, "windows"],//换行风格
"no-multi-spaces": 1,//不能用多余的空格
"no-multi-str": 2,//字符串不能用\换行
"no-multiple-empty-lines": [1, {"max": 2}],//空行最多不能超过2行
"no-native-reassign": 2,//不能重写native对象
"no-negated-in-lhs": 2,//in 操作符的左边不能有!
"no-nested-ternary": 0,//禁止使用嵌套的三目运算
"no-new": 1,//禁止在使用new构造一个实例后不赋值
"no-new-func": 1,//禁止使用new Function
"no-new-object": 2,//禁止使用new Object()
"no-new-require": 2,//禁止使用new require
"no-new-wrappers": 2,//禁止使用new创建包装实例,new String new Boolean new Number
"no-obj-calls": 2,//不能调用内置的全局对象,比如Math() JSON()
"no-octal": 2,//禁止使用八进制数字
"no-octal-escape": 2,//禁止使用八进制转义序列
"no-param-reassign": 2,//禁止给参数重新赋值
"no-path-concat": 0,//node中不能使用__dirname或__filename做路径拼接
"no-plusplus": 0,//禁止使用++,--
"no-process-env": 0,//禁止使用process.env
"no-process-exit": 0,//禁止使用process.exit()
"no-proto": 2,//禁止使用__proto__属性
"no-redeclare": 2,//禁止重复声明变量
"no-regex-spaces": 2,//禁止在正则表达式字面量中使用多个空格 /foo bar/
"no-restricted-modules": 0,//如果禁用了指定模块,使用就会报错
"no-return-assign": 1,//return 语句中不能有赋值表达式
"no-script-url": 0,//禁止使用javascript:void(0)
"no-self-compare": 2,//不能比较自身
"no-sequences": 0,//禁止使用逗号运算符
"no-shadow": 2,//外部作用域中的变量不能与它所包含的作用域中的变量或参数同名
"no-shadow-restricted-names": 2,//严格模式中规定的限制标识符不能作为声明时的变量名使用
"no-spaced-func": 2,//函数调用时 函数名与()之间不能有空格
"no-sparse-arrays": 2,//禁止稀疏数组, [1,,2]
"no-sync": 0,//nodejs 禁止同步方法
"no-ternary": 0,//禁止使用三目运算符
"no-trailing-spaces": 1,//一行结束后面不要有空格
"no-this-before-super": 0,//在调用super()之前不能使用this或super
"no-throw-literal": 2,//禁止抛出字面量错误 throw "error";
"no-undef": 1,//不能有未定义的变量
"no-undef-init": 2,//变量初始化时不能直接给它赋值为undefined
"no-undefined": 2,//不能使用undefined
"no-unexpected-multiline": 2,//避免多行表达式
"no-underscore-dangle": 1,//标识符不能以_开头或结尾
"no-unneeded-ternary": 2,//禁止不必要的嵌套 var isYes = answer === 1 ? true : false;
"no-unreachable": 2,//不能有无法执行的代码
"no-unused-expressions": 2,//禁止无用的表达式
"no-unused-vars": [2, {"vars": "all", "args": "after-used"}],//不能有声明后未被使用的变量或参数
"no-use-before-define": 2,//未定义前不能使用
"no-useless-call": 2,//禁止不必要的call和apply
"no-void": 2,//禁用void操作符
"no-var": 0,//禁用var,用let和const代替
"no-warning-comments": [1, { "terms": ["todo", "fixme", "xxx"], "location": "start" }],//不能有警告备注
"no-with": 2,//禁用with
"array-bracket-spacing": [2, "never"],//是否允许非空数组里面有多余的空格
"arrow-parens": 0,//箭头函数用小括号括起来
"arrow-spacing": 0,//=>的前/后括号
"accessor-pairs": 0,//在对象中使用getter/setter
"block-scoped-var": 0,//块语句中使用var
"brace-style": [1, "1tbs"],//大括号风格
"callback-return": 1,//避免多次调用回调什么的
"camelcase": 2,//强制驼峰法命名
"comma-dangle": [2, "never"],//对象字面量项尾不能有逗号
"comma-spacing": 0,//逗号前后的空格
"comma-style": [2, "last"],//逗号风格,换行时在行首还是行尾
"complexity": [0, 11],//循环复杂度
"computed-property-spacing": [0, "never"],//是否允许计算后的键名什么的
"consistent-return": 0,//return 后面是否允许省略
"consistent-this": [2, "that"],//this别名
"constructor-super": 0,//非派生类不能调用super,派生类必须调用super
"curly": [2, "all"],//必须使用 if(){} 中的{}
"default-case": 2,//switch语句最后必须有default
"dot-location": 0,//对象访问符的位置,换行的时候在行首还是行尾
"dot-notation": [0, { "allowKeywords": true }],//避免不必要的方括号
"eol-last": 0,//文件以单一的换行符结束
"eqeqeq": 2,//必须使用全等
"func-names": 0,//函数表达式必须有名字
"func-style": [0, "declaration"],//函数风格,规定只能使用函数声明/函数表达式
"generator-star-spacing": 0,//生成器函数*的前后空格
"guard-for-in": 0,//for in循环要用if语句过滤
"handle-callback-err": 0,//nodejs 处理错误
"id-length": 0,//变量名长度
"indent": [2, 4],//缩进风格
"init-declarations": 0,//声明时必须赋初值
"key-spacing": [0, { "beforeColon": false, "afterColon": true }],//对象字面量中冒号的前后空格
"lines-around-comment": 0,//行前/行后备注
"max-depth": [0, 4],//嵌套块深度
"max-len": [0, 80, 4],//字符串最大长度
"max-nested-callbacks": [0, 2],//回调嵌套深度
"max-params": [0, 3],//函数最多只能有3个参数
"max-statements": [0, 10],//函数内最多有几个声明
"new-cap": 2,//函数名首行大写必须使用new方式调用,首行小写必须用不带new方式调用
"new-parens": 2,//new时必须加小括号
"newline-after-var": 2,//变量声明后是否需要空一行
"object-curly-spacing": [0, "never"],//大括号内是否允许不必要的空格
"object-shorthand": 0,//强制对象字面量缩写语法
"one-var": 1,//连续声明
"operator-assignment": [0, "always"],//赋值运算符 += -=什么的
"operator-linebreak": [2, "after"],//换行时运算符在行尾还是行首
"padded-blocks": 0,//块语句内行首行尾是否要空行
"prefer-const": 0,//首选const
"prefer-spread": 0,//首选展开运算
"prefer-reflect": 0,//首选Reflect的方法
"quotes": [1, "single"],//引号类型 `` "" ''
"quote-props":[2, "always"],//对象字面量中的属性名是否强制双引号
"radix": 2,//parseInt必须指定第二个参数
"id-match": 0,//命名检测
"require-yield": 0,//生成器函数必须有yield
"semi": [2, "always"],//语句强制分号结尾
"semi-spacing": [0, {"before": false, "after": true}],//分号前后空格
"sort-vars": 0,//变量声明时排序
"space-after-keywords": [0, "always"],//关键字后面是否要空一格
"space-before-blocks": [0, "always"],//不以新行开始的块{前面要不要有空格
"space-before-function-paren": [0, "always"],//函数定义时括号前面要不要有空格
"space-in-parens": [0, "never"],//小括号里面要不要有空格
"space-infix-ops": 0,//中缀操作符周围要不要有空格
"space-return-throw-case": 2,//return throw case后面要不要加空格
"space-unary-ops": [0, { "words": true, "nonwords": false }],//一元运算符的前/后要不要加空格
"spaced-comment": 0,//注释风格要不要有空格什么的
"strict": 2,//使用严格模式
"use-isnan": 2,//禁止比较时使用NaN,只能用isNaN()
"valid-jsdoc": 0,//jsdoc规则
"valid-typeof": 2,//必须使用合法的typeof的值
"vars-on-top": 2,//var必须放在作用域顶部
"wrap-iife": [2, "inside"],//立即执行函数表达式的小括号风格
"wrap-regex": 0,//正则表达式字面量用小括号包起来
"yoda": [2, "never"]//禁止尤达条件