前端Vue3入门:Vite创建项目和使用

2023-07-1011:35:58WEB前端开发Comments915 views字数 5715阅读模式

前端Vue3入门:Vite创建项目和使用文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

前言文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

vite是下一代前端开发与构建工具,目前官方推荐使用vite来构建项目。下面我们来看看如何创建vue3项目。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

创建项目文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

官方提供了多种创建命令,如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

npm init vite@latest
yarn create vite
pnpm create vite

根据自己的情况选择合适的命令即可,我使用的是pnpm,所以:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

pnpm create vite

然后会让给你输入一个项目名称。再选择一个framework,因为我们创建vue3项目,所以选择vue即可。再选择代码语言,我习惯使用JavaScript。如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

✔ Project name: … logistics-systemSelect a framework: › VueSelect a variant: › JavaScript

项目创建完成会提示你后续需要做的工作,如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

  cd logistics-system  pnpm install  pnpm run dev

运行项目文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

根据提示操作即可,先进入项目,然后执行文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

pnpm install

会自动安装所有依赖,安装完成后执行pnpm run devpnpm dev就可以运行项目了,这时候可以看到:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  press h to show help

说明项目成功运行起来了,访问http://localhost:5173/ 即可看到默认页面了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

配置项目文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

成功创建并运行项目后,下面我们就需要进行一些配置,这样方便我们后续开发。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

setting.json文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

vscode可以在项目配置个性的设定,首先需要创建setting.json文件,在vscode中点击左下角的设置按钮,选择命令面板(或者直接使用快捷键 shift+command+p),然后搜索“setting.json”,选择“Open Workspace Setting(JSON)”即可。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

然后就可以看到在项目的.vscode目录下新建了一个setting.json文件,当然这个是个空文件,我们按照相关规则进行配置即可,下面是一个示例:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

{  "files.autoSave": "off",  "git.autofetch": true,  "files.associations": {    "*.cjson": "jsonc",    "*.wxss": "css",    "*.wxs": "javascript",    "*.wpy": "javascriptreact",    "*.py": "python"  },  "emmet.includeLanguages": {    "wxml": "html"  },  "minapp-vscode.disableAutoConfig": true,  "git.confirmSync": false,  "search.actionsPosition": "right",  "search.exclude": {    "**/dist": true  },  "[javascript]": {    "editor.defaultFormatter": "esbenp.prettier-vscode"  },  "editor.suggestSelection": "first",  "files.exclude": {    "**/node_modules": true,    "*/node_modules": true  },  "sync.gist": "686f9b0e863088a613cdc96e5bc81c55",  "[less]": {    "editor.defaultFormatter": "esbenp.prettier-vscode"  },  "[vue]": {    "editor.defaultFormatter": "esbenp.prettier-vscode"  },  "beautify.language": {    "js": {      "type": ["javascript", "json", "jsonc"],      "filename": [".jshintrc", ".jsbeautifyrc"]    },    "css": ["css", "less", "scss"],    "html": ["htm", "html"]  },  "editor.tabSize": 2,  "sync.autoUpload": true,  "sync.forceUpload": false,  "sync.forceDownload": false,  "sync.autoDownload": true,  "beautify.config": "",  "prettier.trailingComma": "none",  "prettier.arrowParens": "avoid",  "editor.fontSize": 13,  // "workbench.colorTheme": "Visual Studio Dark",  "editor.accessibilitySupport": "on",  "diffEditor.ignoreTrimWhitespace": false,  "editor.quickSuggestions": {    "strings": true  },  "editor.rulers": [],  "[html]": {    "editor.defaultFormatter": "vscode.html-language-features"  },  "extensions.closeExtensionDetailsOnViewChange": true,  "[javascriptreact]": {    "editor.defaultFormatter": "svipas.prettier-plus"  },  "[jsonc]": {    "editor.defaultFormatter": "esbenp.prettier-vscode"  },  "[json]": {    "editor.defaultFormatter": "vscode.json-language-features"  },  "[typescript]": {    "editor.defaultFormatter": "esbenp.prettier-vscode"  },  "[typescriptreact]": {    "editor.defaultFormatter": "esbenp.prettier-vscode"  },  "eslint.format.enable": true,  "editor.formatOnSave": true,  "prettier.singleQuote": false,  "prettier.semi": true}

注意:这里使用了格式化配置,需要先在vscode中安装插件prettier。这样当编辑文件后保存的时候就会自动进行格式化。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

src别名文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

在vite.config.js中为src目录配置一个别名,如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

import { defineConfig } from "vite";import vue from "@vitejs/plugin-vue";import path from "path";...
// https://vitejs.dev/config/export default defineConfig({  resolve: {    alias: {      "@": path.resolve(__dirname, "src")    }  },  plugins: [vue()]  ...});

这样在import的时候,就可以直接使用“@/...”了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

但是开发过程中会发现输入"@"并没有智能补全的提示,还需要在jsconfig.json(没有则创建一个)中配置一下,如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

{  "compilerOptions": {    "target": "es5",    "module": "esnext",    "baseUrl": "./",    "jsx": "preserve",    "moduleResolution": "node",    "emitDecoratorMetadata": true,    "experimentalDecorators": true,    "paths": {      "@/*": ["./src/*"]    },    "lib": ["esnext", "dom", "dom.iterable", "scripthost"]  },  "exclude": ["node_modules"]}

在paths中配置一下,然后需要重启一下vscode,否则无法生效。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

开启https文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

在vite.config.js中可以进行服务器相关配置,比如端口、代理、开启https,如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

import { defineConfig } from "vite";import vue from "@vitejs/plugin-vue";import path from "path";

export default defineConfig({  resolve: {    ...  },  plugins: [    vue()  ],  base: "/", // 打包路径  server: {    host: "0.0.0.0",    port: 3300, // 服务端口号    open: true, // 服务启动时是否自动打开浏览器    cors: true, // 允许跨域    https: true    // proxy: {    //   "/api/": {    //     target: "https://xxx.xxx.cn",    //     ws: true,    //     changeOrigin: true    //   }    // }  }});

这样当我们执行pnpm dev开启服务后会自动打开浏览器,并且以https的方式访问。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

但是这里有一个问题,在vite3之后单独开启https并不够,这时候运行服务打开后会发现打不开页面,提示“协议不受支持”。官方文档这样说的:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

server.https¶

  • 类型:  boolean | https.ServerOptions

启用 TLS + HTTP/2。注意:当 server.proxy 选项 也被使用时,将会仅使用 TLS。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

这个值也可以是一个传递给 https.createServer() 的 选项对象。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

需要一个合法可用的证书。对基本使用的配置需求来说,你可以添加 @vitejs/plugin-basic-ssl 到项目插件中,它会自动创建和缓存一个自签名的证书。但我们推荐你创建和使用你自己的证书。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

所以还需要安装一个@vitejs/plugin-basic-ssl插件,执行命令文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

pnpm install @vitejs/plugin-basic-ssl -D

在开发环境使用即可,线上有正式签名。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

然后在vite.config.js中进行配置,如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

...import basicSsl from "@vitejs/plugin-basic-ssl";
export default defineConfig({  resolve: {    ...  },  plugins: [    ...    vue(),    basicSsl()  ],  base: "/", // 打包路径  server: {    host: "0.0.0.0",    port: 3300, // 服务端口号    open: true, // 服务启动时是否自动打开浏览器    cors: true, // 允许跨域    https: true    // proxy: {    //   "/api/": {    //     target: "https://xxx.xxx.cn",    //     ws: true,    //     changeOrigin: true    //   }    // }  },  ...});

这样就可以正常访问了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

代理文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

上面提到可以在vite.config.js配置代理,通过代理可以解决跨越请求的问题。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

比如我们在本机(localhost)上调试,请求服务端接口的时候因为host不同导致跨域,这样就导致cookie带不过去,但是服务端接口又是通过cookie来检验用户的,所以接口请求不成功。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

类似的情况就可以用代理来解决,以axios为例,具体怎么使用这里就不细说了,这里只关注请求接口的代码,如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

export async function getUserInfo() {  return request({    url: "https://xxx.xxx.com/userInfo",    method: "GET"  }).catch(e => e);}

一个请求用户信息的接口,本地调试cookie带不过去,导致获取不到数据。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

我们先设置一个代理,如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

...
export default defineConfig({  resolve: {    ...  },  plugins: [    ...  ],  base: "/", // 打包路径  server: {    host: "0.0.0.0",    port: 3300,     open: true,     cors: true,     https: true    proxy: {  //设置代理      "/api": {        target: "https://xxx.xxx.com",        changeOrigin: true,        rewrite: path => path.replace(/^\/api/, "")      }    }  },  ...});

代理的target就是原服务接口的host,这里我们将“/api”路径代理到原接口,简单来说就是将 https://localhost:3300/api/xxx代理到https://xxx.xxx.com/xxx文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

以上面用户信息接口为例,就是将 https://localhost:3300/api/userInfo代理到https://xxx.xxx.com/userInfo文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

这里的"/api"是为了与前端页面路径进行区分,所以在代理的时候需要通过rewrite去掉。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

然后修改请求如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

export async function getUserInfo() {  return request({    url: "/api/userInfo",    method: "GET"  }).catch(e => e);}

这样请求端口的时候因为是“localhost”,不跨域所以cookie正常,然后代理到原服务端接口就可以将cookie带过去了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

代理还有另外一个作用,当前端页面是https的时候,如果服务端接口是http则无法请求,浏览器会限制。通过设置代理就可以正常进行请求了。比如上面测试环境,就是将https://localhost:3300/apidev/xxx代理到http://dev.xxx.com/xxx文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/51190.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/gcs/51190.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定