Vue-cli 脚手架使用/自定义脚手架/错误解决/跨域解决

说明

  • vue-cli是vue官方提供的脚手架工具 command line interface client
  • 最新的版本是4,
  • 3.x版本与4.x版本变化不大, 但3.x相对于2.x的版本变化特别大
  • 在线文档: https://cli.vuejs.org/zh/

创建脚手架4/3的vue项目, 并运行

npm install -g @vue/cli

vue create vue-demo

npm run serve

创建脚手架2的vue项目

npm install -g @vue/cli-init

vue init webpack vue-demo

npm run dev

模板项目的结构

vue-cli2脚手架项目结构

gshop
	|-- build : webpack相关的配置文件夹(基本不需要修改)
	|-- config: webpack相关的配置文件夹(基本不需要修改)
		|-- index.js: 指定的后台服务的端口号和静态资源文件夹
	|-- node_modules
	|-- src : 源码文件夹
		|-- main.js: 应用入口js
	|-- static: 静态资源文件夹
	|-- .babelrc: babel的配置文件
	|-- .editorconfig: 通过编辑器的编码/格式进行一定的配置
	|-- .eslintignore: eslint检查忽略的配置
	|-- .eslintrc.js: eslint检查的配置
	|-- .gitignore: git版本管制忽略的配置
	|-- index.html: 主页面文件
	|-- package.json: 应用包配置文件 
	|-- README.md: 应用描述说明的readme文件

vue-cli3脚手架项目结构

gshop
	|-- node_modules
	|-- public 静态资源
       |-- index.html: 主页面文件,里面的no script页面不支持js的时候就显示这个
	|-- src
	   |-- main.js: 应用入口js
	|-- babel.config.js: babel的配置文件
	|-- vue.config.js: vue的配置文件
	|-- .gitignore: git版本管制忽略的配置

脚手架3相对于脚手架2的变化

  1. webpack配置
    (1) 2: 配置是暴露的, 我们可以直接在里面修改配置
    (2) 3: 配置是包装隐藏了, 需要通过脚手架扩展的vue.config.js来配置
  2. 运行启动命令
    (1) 2: npm run dev
    (2) 3: npm run serve

自定义

vue create xxx

Your connection to the default yarn registry seems to be slow.
Use https://registry.npm.taobao.org for faster installation?
您与默认纱线注册表的连接似乎很慢。
使用https://registry.npm.taobao.org进行更快的安装? Y

Manually select features

在这里插入图片描述

选择插件

Check the features needed for your project
检查项目所需的功能

  • eslint:语法检查,是不是按照规定代码去写的 (airbnb是目前著名风格规范)
  • css 预处理 less/saas
  • 空格可以选择和取消,回车确认
    在这里插入图片描述

选择vue版本

Choose a version of Vue.js that you want to start the project with (Use arrow keys)
选择要使用(使用箭头键)启动项目的Vue.js版本)
在这里插入图片描述

选择css预处理器

Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default)
选择CSS预处理器(默认情况下支持POST CSS、Autoprefixer和CSS模块)
在这里插入图片描述

格式化程序配置

Pick a linter / formatter config:
选择一个linter/格式化程序配置:
在这里插入图片描述

代码检查时机

  • lint on save 写代码的时候检查
  • commit 提交的时候检查
    在这里插入图片描述

配置文件位置

Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
您更喜欢在哪里放置Babel、ESLint等的配置。? (使用箭头键)
在这里插入图片描述

保存此配置?

Save this as a preset for future projects
将此保存为未来项目的预置
在这里插入图片描述

yarn ? npm ?

Pick the package manager to use when installing dependencies: (Use arrow keys)
在安装依赖项时选择要使用的包管理器:(使用箭头键)
在这里插入图片描述

DONE

在这里插入图片描述
在这里插入图片描述

进入文件夹,运行

在这里插入图片描述

npm run server

在这里插入图片描述

Done

在这里插入图片描述

自己第一个小练习

删除src下面所有

在这里插入图片描述

新建main.js入口文件

import Vue from 'vue';

import App from './App.vue';

new Vue({
  render: (h) => h(App),
}).$mount('#app');

新建App.vue

<template>
  <!-- 模板页面,写页面的 -->
  <div class="app">
    <h1>hello vue cli</h1>
    <p>{{ num }}</p>
    <button @click="handle">数字加加</button>
  </div>
</template>

<script>
// 写组件配置对象
export default {
  name: " div ",
  data() {
    return {
      num: 0,
    };
  },
  methods: {
    handle() {
      this.num += 1;
    },
  },
};
</script>

<style lang='less'>
* {
  margin: 0;
  padding: 0;
}
html,
body {
  height: 100%;
}
.app {
  height: 100%;
  background-color: yellowgreen;
}
</style>

npm run serve/yarn serve

package.json默认

  • 修改之后记得重启服务器
{
  "name": "myvue",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.6.5",
    "vue": "^2.6.11"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/eslint-config-airbnb": "^5.0.2",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-vue": "^6.2.2",
    "less": "^3.0.4",
    "less-loader": "^5.0.0",
    "vue-template-compiler": "^2.6.11"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "@vue/airbnb"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}

done

在这里插入图片描述

效果

在这里插入图片描述

常见报错解决

Strings must use singlequote quotes

  • 字符串必须使用单引号
    在这里插入图片描述

Missing file extension “vue” for “./App”

  • 缺少"./App"的文件扩展名"vue"
    在这里插入图片描述
  • 解决
    在这里插入图片描述

Expected parentheses around arrow function argument

  • 箭头函数参数周围的括号
    在这里插入图片描述
    在这里插入图片描述

Missing trailing comma comma-dangle

  • 末尾逗号不见了
    在这里插入图片描述

在这里插入图片描述

Missing semicolon semi

  • 缺少分号半
    在这里插入图片描述
    在这里插入图片描述

Unary operator ‘++’ used

  • 使用了一元操作符“++”
    在这里插入图片描述
    在这里插入图片描述

Newline required at end of file but not found eol-last

  • 文件末尾需要换行,但没有找到eol-last
    在这里插入图片描述

Expected linebreaks to be ‘LF’ but found ‘CRLF’ linebreak-style

  • 期望换行符为’LF’,但发现’CRLF’换行样式
    在这里插入图片描述

关闭eslint检查 package.json

  • 关闭以后可以忽略上面的报错,不再进行检查
  • 在rules里面去做
    在这里插入图片描述

警告信息展示

  • 根据需求处理就好
    在这里插入图片描述

跨域问题解决

App.vue

<template>
  <button @click="handle">点击按钮发送请求</button>
</template>

<script>
import axios from 'axios';

export default {
  name: 'App',
  methods: {
    handle() {
      axios
        .get('http://localhost:3000/home')
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>

<style>
</style>

在这里插入图片描述

server

// import是ES6的语法,启动服务器需要node环境,是CommentJs语法,需要require引入
// import express from "express";

const express = require("express");

const app = express();

app.get("/home", (request, response) => {
  // cose解决跨域
//   response.set("Access-Control-Allow-Origin", "*");
  response.json({
    name: "rolls",
    color: "green",
    engine: "N73"
  });
});

// 启动服务器
app.listen(3000, "localhost", err => {
  if (err) {
    alert("服务器启动失败,请重试");
    console.log(err);
    return;
  }
  console.log("服务器启动成功了,请访问http://localhost:3000");
});


运行

Access to XMLHttpRequest at ‘http://localhost:3000/home’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

在“http://localhost:3000/home”from origin“http://localhost:8080”上对XMLHttpRequest的访问已被CORS策略阻止:被请求的资源上没有“Access-Control-Allow-Origin”头。

在这里插入图片描述

解决

vuecli解决跨域官方文档

  • 在根目录下创建vue.config.js

vue.config.js 修改vue脚手架的配置文件
注意文件目录不能出错:项目根目录
当你启动脚手架时,读取这个文件配置从而修改脚手架配置

  • 方式一
 // 因为我要发访问服务器,让服务器代替我去获取数据返回给我,所以要改访问的地址
        // .get('http://localhost:8080/home')  这个是错误的
        .get('/home')
module.exports = {
  devServer: {
    /*  开启代理服务器,设置目标服务器地址为 http://localhost:3000,
      将来如果客户端发送请求到代理服务器上,代理服务器会自动将请求转发到目标服务器上 */
    proxy: "http://localhost:3000"
  }
};

成功
在这里插入图片描述

  • 方式二
// 修改请求地址
     .get('/api/home')
     .then((res) => {
       console.log(res);
     })
     .catch((err) => {
       console.log(err);
     });

module.exports = {
  devServer: {
    proxy: {
      /*
          当请求地址以 /api 开头,当前代理配置生效
          会将请求地址重写,将请求地址的/api地址替换为空,例如:
            请求地址:http://localhost:8080/api/search/users
            重写为:http://localhost:8080/search/users
          并且转发请求到 target 地址(目标服务器地址)去
            http://localhost:3000/search/users
        */
      "/api": {
        target: "http://localhost:3000",
        // 重写请求地址
        pathRewrite: { "^/api": "" }
      }
      // '/v2/api': {
      //   target: 'http://localhost:3001',
      //   // 重写请求地址
      //   pathRewrite: {'^/api' : ''}
      // }
    }
  }
};

在这里插入图片描述

简写路径

  • 需要配合jsconfig.json文件使用
// 将来处理这个文件会运行在nodejs环境,nodejs处理路径用path
const path = require("path");
module.exports = {
  devServer: {
    proxy: {
      "/api": {
        target: "http://localhost:3000",
        pathRewrite: { "^/api": "" }
      }
    }
  },
  // 当前配置会和vue配置合并,我们的生效
  configureWebpack: {
    resolve: {
      alias: {
        //配置路径别名,将来@views就代表这个目录
        /* 
          比如 import Search from "./Views/Serach"
          可以 import Search from "@views/Search"
          会把一些常用目录配置上去
        */
        // 符合页面路径
        "@views": path.resolve(__dirname, "src/views/"),
        // 公共资源 样式 图片
        "@assets": path.resolve(__dirname, "src/assets"),
        //  公共组件路径
        "@comps": path.resolve(__dirname, "src/components"),
        // 集中式管理数据路径
        "@store": path.resolve(__dirname, "src/store"),
        // 工具,js函数路径
        "@utils": path.resolve(__dirname, "src/utils")
      }
    }
  }
};

jsconfig.json

  • 路径别名没有提示,所以配置vscode配置文件就好,一定要根目录,让写路径的时候有提示
  • https://code.visualstudio.com/docs/languages/jsconfig
    在这里插入图片描述
    在这里插入图片描述
    == 这个文件一定要单独打开==也就是只要这个文件夹在vscode运行,否则嵌套太深找不到
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@views/*": ["./src/views/*"],
      "@assets/*": ["./src/assets/*"],
      "@comps/*": ["./src/components/*"],
      "@store/*": ["./src/store/*"],
      "@utils/*": ["./src/utils/*"]
    }
  },
  "exclude": ["node_modules"]
}

publicPath

  • 将来所有资源输出的路径

configureWebpack

配置参考-官方

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值