分享一篇使用 Vite 创建 Vue3 项目的入门指南

24bdc144e403d72170b19999a3edbe4f.jpeg

74f38b99ddd7a06c717daa113596081d.png

前言

vite是下一代前端开发与构建工具,目前官方推荐使用vite来构建项目。下面我们来看看如何创建vue3项目。

eb12d461972e7bfd83937b133cfda1d3.png

创建项目

官方提供了多种创建命令,如下:

npm init vite@latest


yarn create vite


pnpm create vite

根据自己的情况选择合适的命令即可,我使用的是pnpm,所以:

pnpm create vite

然后会让给你输入一个项目名称。再选择一个framework,因为我们创建vue3项目,所以选择vue即可。再选择代码语言,我习惯使用JavaScript。如下:

✔ Project name: … logistics-system
✔ Select a framework: › Vue
✔ Select a variant: › JavaScript

项目创建完成会提示你后续需要做的工作,如下:

cd logistics-system
  pnpm install
  pnpm run dev

运行项目

根据提示操作即可,先进入项目,然后执行

pnpm install

会自动安装所有依赖,安装完成后执行pnpm run devpnpm dev就可以运行项目了,这时候可以看到:

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

说明项目成功运行起来了,访问http://localhost:5173/ 即可看到默认页面了。


8a5d92a2c85af62b9bb8c3119d0df2ae.png

配置项目

成功创建并运行项目后,下面我们就需要进行一些配置,这样方便我们后续开发。

setting.json

vscode可以在项目配置个性的设定,首先需要创建setting.json文件,在vscode中点击左下角的设置按钮,选择命令面板(或者直接使用快捷键 shift+command+p),然后搜索“setting.json”,选择“Open Workspace Setting(JSON)”即可。

然后就可以看到在项目的.vscode目录下新建了一个setting.json文件,当然这个是个空文件,我们按照相关规则进行配置即可,下面是一个示例:

{
  "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。这样当编辑文件后保存的时候就会自动进行格式化。

src别名

在vite.config.js中为src目录配置一个别名,如下:

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的时候,就可以直接使用“@/...”了。

但是开发过程中会发现输入"@"并没有智能补全的提示,还需要在jsconfig.json(没有则创建一个)中配置一下,如下:

{
  "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,否则无法生效。

9de0edbdc73126abefdee1d246c24aa3.png

开启https

在vite.config.js中可以进行服务器相关配置,比如端口、代理、开启https,如下:

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的方式访问。

但是这里有一个问题,在vite3之后单独开启https并不够,这时候运行服务打开后会发现打不开页面,提示“协议不受支持”。官方文档这样说的:

server.https¶

  • 类型:  boolean | https.ServerOptions

启用 TLS + HTTP/2。注意:当 server.proxy 选项 也被使用时,将会仅使用 TLS。

这个值也可以是一个传递给 https.createServer() 的 选项对象。

需要一个合法可用的证书。对基本使用的配置需求来说,你可以添加 @vitejs/plugin-basic-ssl 到项目插件中,它会自动创建和缓存一个自签名的证书。但我们推荐你创建和使用你自己的证书。

所以还需要安装一个@vitejs/plugin-basic-ssl插件,执行命令

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

在开发环境使用即可,线上有正式签名。

然后在vite.config.js中进行配置,如下:

...
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
    //   }
    // }
  },
  ...
});

这样就可以正常访问了。

2f5aab9e8bba40d2aab8cdf97e8b1898.png

代理

上面提到可以在vite.config.js配置代理,通过代理可以解决跨越请求的问题。

比如我们在本机(localhost)上调试,请求服务端接口的时候因为host不同导致跨域,这样就导致cookie带不过去,但是服务端接口又是通过cookie来检验用户的,所以接口请求不成功。

类似的情况就可以用代理来解决,以axios为例,具体怎么使用这里就不细说了,这里只关注请求接口的代码,如下:

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

一个请求用户信息的接口,本地调试cookie带不过去,导致获取不到数据。

我们先设置一个代理,如下:

...


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://localhost:3300/api/userInfo代理到https://xxx.xxx.com/userInfo

这里的"/api"是为了与前端页面路径进行区分,所以在代理的时候需要通过rewrite去掉。

然后修改请求如下:

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

这样请求端口的时候因为是“localhost”,不跨域所以cookie正常,然后代理到原服务端接口就可以将cookie带过去了。

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

粉丝福利

分享一个现代感十足的博客源码(Headless blog),当下流行的无头博客方案,这个源码使用了React、GatsbyJS v5 技术,并拥有九个不同类型的博客风格。此博客不仅支持本地Markdown文件,还支持Contentful CMS、Strapi CMS、Netlify CMS和Sanity CMS等内容管理系统,让你能够自由创作博客文章,喜欢的赶紧收下吧。

猜你喜欢

转载自blog.csdn.net/Ed7zgeE9X/article/details/132517610