Vue project templates – Patterns and environment variables

preface

The last few articles didn’t notice that the project directory structure screenshot shows up. I’m sure you all know that vUE scaffolding has a mode and environment variable configuration. So this article doesn’t help much. In fact, this article is the process of recording my own learning mode and environment. Environment variable and model | Vite Chinese website (vitejs. Cn)

Create environment-related files

Create development environment files

Create the.env.development file in the project root directory

ENV = 'development' #base api , This API is the API VITE_APP_BASE_API node community = 'https://cnodejs.org/api/v1' VITE_APP_TITLE = vue project template (development environment)Copy the code

The.env.development file is loaded in NPM run dev, so it corresponds to the variables of the development environment.

Create production environment files

Create the.env.development file in the project root directory

ENV = 'production' # base API VITE_APP_BASE_API = 'http://www.production.com' VITE_APP_TITLE = vue project template (production)Copy the code

The.env.development file is loaded in the NPM run build, so it corresponds to the production environment variables.

Set up a request test

Create an API folder

Create API folder in project SRC, base. Js file and home folder, and index.js file in home folder.

Base. Js file

//base.js

const baseUrl = import.meta.env.VITE_APP_BASE_API;
export default baseUrl;
Copy the code

index.js

//index.js import base from '.. /base'; // Import axios from '.. /.. /request/http'; Axios export function getData(params) {return axios.get(' ${base}/topics', {params})}Copy the code

The index.js file introduces AXIos, where the installation steps are omitted. After installing axios, you can directly import axios from ‘.. /.. /request/http’; // import axios from ‘axios’; Ready to use.

Called in the helloWorld.vue file

<template> <h1> {{MSG}} <span> ha-ha </span> </h1> <el-button> Element </el-button> </template> <script lang="ts"> import { ref, defineComponent } from "vue"; import { getData } from ".. /api/home"; const env = import.meta.env; export default defineComponent({ name: "HelloWorld", props: { msg: { type: String, required: false, }, }, setup: () => { const count = ref(0); / * * * * * * * * * * * * * * * * * call API * * * * * * * * * * * * * * * * * * * * / getData ({page: 1, the TAB: "ask", limit: 10, mdrender: false, }).then((res:object) => { console.log(res, 988888); }); / * * * * * * * * * * * * * * * * * * call API * * * * * * * * * * * * * * * * * * * / return {count}; }}); </script> <style scoped lang="less"> h1 { color: red; span { color: #333; } } </style>Copy the code

Run NPM run dev

Request successful, variable of.env.development file called successfully.