foreword
Vite is a next-generation front-end development and construction tool. Currently, it is officially recommended to use vite to build projects. Let's take a look at how to create a vue3 project.
create project
The official provides a variety of creation commands, as follows:
npm init vite@latest
yarn create vite
pnpm create vite
Just choose the appropriate command according to your own situation. I use pnpm, so:
pnpm create vite
Then it will ask you to enter a project name. Choose another framework, because we create a vue3 project, so just choose vue. Then choose the code language, I am used to using JavaScript. as follows:
✔ Project name: … logistics-system
✔ Select a framework: › Vue
✔ Select a variant: › JavaScript
After the project is created, you will be prompted for the follow-up work, as follows:
cd logistics-system
pnpm install
pnpm run dev
run project
Just follow the prompts, first enter the project, and then execute
pnpm install
All dependencies will be installed automatically. After the installation is complete, execute pnpm run dev
or pnpm dev
run the project. At this time, you can see:
➜ Local: http://localhost:5173/
➜ Network: use --host to expose
➜ press h to show help
It means that the project is running successfully, and you can see the default page by visiting http://localhost:5173/.
configuration items
After successfully creating and running the project, we need to make some configurations to facilitate our subsequent development.
setting.json
Vscode can configure individual settings in the project. First, you need to create a setting.json file. Click the settings button in the lower left corner of vscode, select the command panel (or directly use the shortcut key shift+command+p), and search for "setting.json ", select "Open Workspace Setting (JSON)".
Then you can see that a new setting.json file has been created in the .vscode directory of the project. Of course, this is an empty file. We can configure it according to the relevant rules. The following is an example:
{
"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
}
Note: The formatting configuration is used here, and the plug-in prettier needs to be installed in vscode first. This will automatically format the file when it is saved after editing.
src alias
Configure an alias for the src directory in vite.config.js, as follows:
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()]
...
});
In this way, when importing, you can directly use "@/...".
However, during the development process, you will find that there is no smart completion prompt for entering "@", and you need to configure it in jsconfig.json (create one if you don't have one), as follows:
{
"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"]
}
Configure it in paths, and then you need to restart vscode, otherwise it will not take effect.
open https
In vite.config.js, you can perform server-related configurations, such as port, proxy, and enable https, as follows:
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
// }
// }
}
});
In this way, when we start pnpm dev
the service, the browser will be automatically opened and accessed in https.
But there is a problem here. It is not enough to enable https after vite3. At this time, after the running service is turned on, it will be found that the page cannot be opened, and it will prompt "protocol is not supported". The official documentation says this:
server.https¶
type:
boolean | https.ServerOptions
Enable TLS + HTTP/2. NOTE: When
server.proxy
option is also used, only TLS will be used.This value can also be an
https.createServer()
options object passed to .A legally available certificate is required. For basic configuration requirements, you can add @vitejs/plugin-basic-ssl to the project plugin, which will automatically create and cache a self-signed certificate. But we recommend that you create and use your own certificates.
So you also need to install a @vitejs/plugin-basic-ssl plugin, execute the command
pnpm install @vitejs/plugin-basic-ssl -D
It can be used in the development environment, and there is an official signature online.
Then configure it in vite.config.js, as follows:
...
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
// }
// }
},
...
});
Then you can access normally.
acting
As mentioned above, the proxy can be configured in vite.config.js, and the problem of crossing requests can be solved through the proxy.
For example, when we debug on this machine (localhost), when requesting the server interface, because the host is different, the cross-domain is caused, which causes the cookie to fail to pass through, but the server interface uses cookies to check the user, so the interface request is unsuccessful. .
A similar situation can be solved with a proxy. Taking axios as an example, I won’t elaborate on how to use it here. Here we only focus on the code of the request interface, as follows:
export async function getUserInfo() {
return request({
url: "https://xxx.xxx.com/userInfo",
method: "GET"
}).catch(e => e);
}
An interface that requests user information, the local debugging cookie cannot be carried over, resulting in the inability to obtain data.
Let's set up a proxy first, as follows:
...
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/, "")
}
}
},
...
});
The target of the proxy is the host of the original service interface. Here we proxy the "/api" path to the original interface https://localhost:3300/api/xxx
.https://xxx.xxx.com/xxx
Taking the above user information interface as an example, it is to https://localhost:3300/api/userInfo
proxy tohttps://xxx.xxx.com/userInfo
The "/api" here is to distinguish it from the front-end page path, so it needs to be removed when proxying rewrite
.
Then modify the request as follows:
export async function getUserInfo() {
return request({
url: "/api/userInfo",
method: "GET"
}).catch(e => e);
}
In this way, when the port is requested, it is "localhost" and does not cross domains, so the cookie is normal, and then the proxy can bring the cookie to the original server interface.
The proxy has another function. When the front-end page is https, if the server interface is http, the request cannot be made, and the browser will limit it. By setting the proxy, the request can be made normally. For example, the above test environment is to https://localhost:3300/apidev/xxx
proxy tohttp://dev.xxx.com/xxx
Fan benefits
Share a modern blog source code (Headless blog), the current popular headless blog solution, this source code uses React, GatsbyJS v5 technology, and has nine different types of blog styles. This blog not only supports local Markdown files, but also supports content management systems such as Contentful CMS, Strapi CMS, Netlify CMS, and Sanity CMS, allowing you to freely create blog articles. If you like it, accept it quickly.