Vue3 Vue CLI multi-environment configuration

Vue3 Vue CLI multi-environment configuration

1. Introduction

This is less troublesome than before. In simple terms, it is to use configuration files to manage multiple environments and realize environment switching.

2. Switching

1. Add development and production configuration files

In the root directory of the web, create a development environment switching configuration file .env.dev with the following content:

NODE_ENV=development
VUE_APP_SERVER=http://127.0.0.1:8880

In the root directory of the web, create an online environment switching configuration file .env.prod with the following content:

NODE_ENV=production
VUE_APP_SERVER=https://www.baidu.com

2. Modify compilation and startup to support multiple environments

Modify in package.json , that is, adjust the original server ,

The sample code is as follows:

{
  "name": "web",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve-dev": "vue-cli-service serve --mode dev --port 8080",
    "serve-prod": "vue-cli-service serve --mode prod",
    "build-dev": "vue-cli-service build --mode dev",
    "build-prod": "vue-cli-service build --mode prod",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "@ant-design/icons-vue": "^5.1.9",
    "ant-design-vue": "^2.0.0-rc.3",
    "axios": "^0.21.0",
    "vue": "^3.0.0",
    "vue-router": "^4.0.0-0",
    "vuex": "^4.0.0-0"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^4.18.0",
    "@typescript-eslint/parser": "^4.18.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-plugin-typescript": "~4.5.0",
    "@vue/cli-plugin-vuex": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "@vue/eslint-config-typescript": "^7.0.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^7.0.0",
    "typescript": "~4.1.5"
  }
}

Click the refresh button in npm on the right to see the effect as follows:

In order to see the effect, we add output log code in main.ts to verify whether the modification is successful.

Add the following code:

console.log('environment',process.env.NODE_ENV);
console.log('server',process.env.VUE_APP_SERVER);


Knowledge points:

  • NODE_ENV is the NODE_ENV variable corresponding to the configuration file
  • VUE_APP_SERVER is the VUE_APP_SERVER variable corresponding to the configuration file

Recompile and start the service. The result is as follows:

3. Modify the axios request address to support multiple environments

Why modify?

Because a system cannot have only one request, and writing the full path for each request will increase the maintenance cost of the code. Therefore, it is better to use a unified configuration for maintenance here.

Because it is global, you only need to modify it in main.ts , reference axios , and set the default access path.

The sample code is as follows:

import {createApp} from 'vue';
import Antd from 'ant-design-vue';
import App from './App.vue';
import 'ant-design-vue/dist/antd.css';
import router from './router';
import store from './store';
import axios from 'axios';
axios.defaults.baseURL=process.env.VUE_APP_SERVER;

//The advantage is that it is easy to develop, but the disadvantage is that the file will be larger when packaged (but it does not affect anything)
createApp(App).use(store).use(router).use(Antd).mount('#app')

console.log('environment', process.env.NODE_ENV);
console.log('server', process.env.VUE_APP_SERVER);


Then, we modify the request address of axios in home , leaving only the path.

The sample code is as follows:

<template>
  <a-layout>
    `<a-layout-sider width="200" style="background: #fff">
      <a-menu
          mode="inline"
          v-model:selectedKeys="selectedKeys2"
          v-model:openKeys="openKeys"
          :style="{ height: '100%', borderRight: 0 }"
      >
        <a-sub-menu key="sub1">
          <template #title>
                <span>
                  <user-outlined />
                  subnav 1
                </span>
          </template>
          <a-menu-item key="1">option1</a-menu-item>
          <a-menu-item key="2">option2</a-menu-item>
          <a-menu-item key="3">option3</a-menu-item>
          <a-menu-item key="4">option4</a-menu-item>
        </a-sub-menu>
        <a-sub-menu key="sub2">
          <template #title>
                <span>
                  <laptop-outlined />
                  subnav 2
                </span>
          </template>
          <a-menu-item key="5">option5</a-menu-item>
          <a-menu-item key="6">option6</a-menu-item>
          <a-menu-item key="7">option7</a-menu-item>
          <a-menu-item key="8">option8</a-menu-item>
        </a-sub-menu>
        <a-sub-menu key="sub3">
          <template #title>
                <span>
                  <notification-outlined />
                  subnav 3
                </span>
          </template>
          <a-menu-item key="9">option9</a-menu-item>
          <a-menu-item key="10">option10</a-menu-item>
          <a-menu-item key="11">option11</a-menu-item>
          <a-menu-item key="12">option12</a-menu-item>
        </a-sub-menu>
      </a-menu>
  </a-layout-sider>
    `
    <a-list item-layout="vertical" size="large"
            :grid="{ gutter: 16, column: 3 }" :data-source="ebooks1">
      <template #renderItem="{ item }">
        <a-list-item key="item.name">
          <template #actions>
          <span v-for="{ type, text } in actions" :key="type">
            <component v-bind:is="type" style="margin-right: 8px"/>
            {{ text }}
          </span>
          </template>
          <a-list-item-meta :description="item.description">
            <template #title>
              <a :href="item.href" rel="external nofollow" >{{ item.name }}</a>
            </template>
            <template #avatar><a-avatar :src="item.cover" /></template>
          </a-list-item-meta>
        </a-list-item>
      </template>
    </a-list>
  </a-layout>
</template>

<script lang="ts">
import {defineComponent, onMounted, reactive, ref, toRef} from 'vue';
import axios from 'axios';
import {LikeOutlined, MessageOutlined, StarOutlined} from '@ant-design/icons-vue';

const listData: Record<string, string>[] = [];

export default defineComponent({
  components:
    StarOutlined,
    LikeOutlined,
    MessageOutlined,
  },
  name: 'Home',
  setup(){
    const pagination = {
      onChange: (page: number) => {
        console.log(page);
      },
      pageSize: 3,
    };
    const actions: Record<string, string>[] = [
      { type: 'StarOutlined', text: '156' },
      { type: 'LikeOutlined', text: '156' },
      { type: 'MessageOutlined', text: '2' },
    ];
    console.log('set up');
    //Use ref for data binding const ebooks=ref();
    // Use reactive data binding const ebooks1 = reactive({books:[]})
    onMounted(()=>{
      axios.get("/ebook/list?name=").then(response => {
        console.log("onMounted");
        const data = response.data;
        ebooks.value = data.content;
        ebooks1.books = data.content;
        console.log(response);
      })
    })
    return {
      pagination,
      actions,
      ebooks1: ebooks,
      ebooks2: toRef(ebooks1, "books")
    }

  }
});
</script>
<style scoped>
.ant-layout-sider {
  float: left;
}

.ant-avatar {
  width: 50px;
  height: 50px;
  line-height: 50px;
  border-radius: 8%;
  margin: 5px 0;
}
</style>

We recompile and start again, and the results are as follows:

From the red circle, it can be seen that axios request address has been modified and the global configuration maintenance has been successfully achieved.

Knowledge points:

  • Multi-environment configuration files should be placed in the web root directory
  • .env.xxx , the suffix xxx corresponds to –mode xxx of the command in package.json
  • Add the –port parameter to modify the startup port
  • Custom variables must start with VUE_APP_
  • By setting axios.defaults.baseURL , you can uniformly set the backend IP port or domain name

This is the end of this article about Vue CLI multi-environment configuration of Vue3. For more relevant Vue CLI multi-environment configuration content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to use Tencent slider verification code in Vue3+Vue-cli4 project
  • Using Vue3 (Part 1) Creating a Vue CLI Project
  • Vue3.0 CLI - 3.2 Routing Basic Tutorial
  • vue3.0 CLI - 2.5 - Understanding the three dimensions of components
  • vue3.0 CLI - 2.4 - Learn forms in the new component Forms.vue

<<:  Analysis and solution of the reason why the frameset tag in HTML cannot be displayed normally

>>:  MySQL integrity constraints definition and example tutorial

Recommend

Solution to MySql service disappearance for unknown reasons

Solution to MySql service disappearance for unkno...

Configuring MySQL and Squel Pro on Mac

In response to the popularity of nodejs, we have ...

How to use MySQL 5.7 temporary tablespace to avoid pitfalls

Introduction MySQL 5.7 aims to be the most secure...

Linux beginners in virtual machines configure IP and restart the network

For those who are new to virtual machines or have...

Solution for installing opencv 3.2.0 in Ubuntu 18.04

Download opencv.zip Install the dependencies ahea...

Docker image creation Dockerfile and commit operations

Build the image There are two main ways to build ...

How to configure multiple projects with the same domain name in Nginx

There are two ways to configure multiple projects...

ElementUI implements cascading selector

This article example shares the specific code of ...

How to use Nginx to carry rtmp live server

This time we set up an rtmp live broadcast server...

How to build gitlab on centos6

Preface The original project was placed on the pu...

jQuery implements breathing carousel

This article shares the specific code of jQuery t...

How to fix the width of table in ie8 and chrome

When the above settings are used in IE8 and Chrome...

How to quickly delete all tables in MySQL without deleting the database

This article uses an example to describe how to q...

Example of CSS3 to achieve div sliding in and out from bottom to top

1. First, you need to use the target selector of ...