New bee mall open source warehouse (Vue 2. X and Vue 3. X H5 mall open source code, with server API interface) : github.com/newbee-ltd

Vue 3.x + Vant 3.x + Vue -router 4.x

This article source address: github.com/Nick930826/…

preface

Recently, the company is going to do a small project. I asked the boss if I could write it with Vue, because the company has always used React, and I mainly want to try Vite. Vite is also made by the master, so I want to try using Vue as the technology stack. The eldest brother asks me: “excrement eats not to eat.” I vaguely felt that the eldest brother was scolding the grandfather, but I could not refute it, so I tried to use Vite + React form to complete a project shelf.

By default, you have installed the Node environment.

knowledge

  • ViteInitialize theReactproject
  • Importing routing plug-insreact-router-dom 
  • The introduction ofAnt DesignComponent library
  • configurationAnt DesignAccording to the need to introduce
  • configurationAnt DesignThe theme color
  • Configure environment variables for packaging and runtimeenv
  • axiosSecondary packaging
  • The path to package static resources
  • ViteSome of the configuration such as the development port,proxyThe agent,aliasAliases etc.

To start the

Initialize the Vite + React project

Here have to sigh with emotion, years ago or Vite 1. X, after the year became 2. X. To illustrate two problems, the grandfather is very active in this project, and there are many uncertain factors. But this does not prevent us to learn it, because it is really sweet and fast. Put an official Chinese document, interested can see the document.

Vite officially offers two ways to initialize a project. One is:

npm init @vitejs/app
Copy the code

You are free to choose the configuration. Another is to directly use the official provided template, one key generation:

# npm 6.x
npm init @vitejs/app vite-react-app --template react

# NPM 7+, additional double horizontal lines are required:
npm init @vitejs/app vite-react-app -- --template react
Copy the code

This tutorial takes the second form and generates the following project:

Follow the steps above to go to the viet-React-app. After installing the package, start the project:

At this point you have successfully set up the Vite + React development environment. 🎉 🎉 🎉

Import the react-router-dom plug-in

Install react-router-dom with the following instructions:

npm i react-router-dom -S
Copy the code

In the project SRC directory, add a container directory to place the page components. In the container directory, add the following contents:

// Index/index.jsx
import React from 'react'

export default function Index() {
  return <div>
    Index
  </div>
}

// About/index.jsx
import React from 'react'

export default function About() {
  return <div>
    About
  </div>
}
Copy the code

Create SRC /router/index.js to configure the route array and add the following content:

// router/index.js
import Index from '.. /container/Index'
import About from '.. /container/About'

const routes = [
  {
    path: "/".component: Index
  },
  {
    path: "/about".component: About
  }
];

export default routes
Copy the code

Import route configuration in app. JSX to switch the browser path and display the corresponding components:

// App.jsx
import React, { useState } from 'react'
import {
  BrowserRouter as Router,
  Switch,
  Route
} from "react-router-dom"
import routes from '.. /src/router'
function App() {
  return <Router>
    <Switch>
      {
        routes.map(route => <Route exact key={route.path} path={route.path}>
          <route.component />
        </Route>)}</Switch>
  </Router>
}

export default App
Copy the code

Start the project NPM run dev, as shown below:

Introduce the Ant Design UI component library

The Ant Design website doesn’t give you the Vite configuration method, so I’m trying to figure it out. First we download the installation package:

npm i antd @ant-design/icons -S
Copy the code

The latest version of icon package is separate, so here we install @ant-design/ ICONS.

After the installation is successful, we first test whether it can successfully run through the global introduction method. Open main. JSX and add styles:

.import 'antd/dist/antd.css'.Copy the code

Go back to Index/index. JSX and change it as follows:

import React from 'react'
import { Button } from 'antd'

export default function Index() {
  return <div>
    <Button type='primary'>Index</Button>
  </div>
}
Copy the code

Restart the project with the browser as follows, indicating that Ant Design has been imported successfully:

At this point we can try to do some optimizations, but let’s first see how big the static resources are after the package is finished in the current situation. Run the NPM run build command as follows:

At first glance, the CSS static resource is 587.96K by introducing the style form globally and directly finishing the package. We try to load the style on demand.

First we install a plugin:

npm i vite-plugin-imp -D
Copy the code

Then add the following contents to the vite. Config.js configuration file:

import { defineConfig } from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'
import vitePluginImp from 'vite-plugin-imp'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    reactRefresh(),
    vitePluginImp({
      libList: [{libName: "antd".style: (name) = > `antd/lib/${name}/style/index.less`,},],})],css: {
    preprocessorOptions: {
      less: {
        // Support inline JavaScript
        javascriptEnabled: true,}}},})Copy the code

Then install the less plug-in package, NPM I less -d, because the above configuration we use less, and we need to configure javascriptEnabled to true, support less inline JS.

Here we remove the import ‘antd/dist/antd. CSS ‘from main.jsx, start NPM run dev again, and you will see that the styles are introduced as needed. Let’s see what the plugin-plugin-imp plug-in does:

There’s a separate button style component in index.jsx. Let’s look at the size of the packaged static resource again:

The CSS style pack is now 40.29KB

Some of you may be concerned that with Button components introduced on different pages, the styles will be repeated. The answer is no. The package builds merge similar items, so the Button style file will only be introduced once.

Custom Ant Design theme colors

During development, you customize a set of theme styles, including margins, text size, borderColor, and so on, according to the needs of the project and the designer’s design (which is a blind drawing). Maybe those of you who used to use Webpack know how to play, but now we use Vite, we need to do the following.

First, open v.config.js and add the following code:

.import path from 'path'
import fs from 'fs'
import lessToJS from 'less-vars-to-js'

const themeVariables = lessToJS(
  fs.readFileSync(path.resolve(__dirname, './config/variables.less'), 'utf8'))...css: {
  preprocessorOptions: {
    less: {
      // Support inline JavaScript
      javascriptEnabled: true.// Override the less variable to customize the style
      modifyVars: themeVariables
    }
  }
}
...
Copy the code

Less-vars-to-js converts the less style to a JSON key pair, but you can also write the JSON key pair directly after the modifyVars attribute.

Then create a new config directory in the root directory and add variables.

/ / custom cover = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
@primary-color: green; // Global dominant color
// Below you can write a variety of overlay styles, here simply overlay a theme color style, let's change to green
Copy the code

Rerun as follows:

So the theme color is changed.

How are environment variables obtained

I searched a lot of information, but I still couldn’t find the answer I needed based on the current ecology of Vite. I put my last hope in Vite’s warehouse issue, but I did search out some things. Here is an aside, if there is any problem, first solve it yourself, go to the corresponding warehouse to see if there is a similar problem that has been solved. Do not always go to the group to ask big guy, big guy is not busy, free to you solve the problem?

Ok, our compasses are turning. When we usually develop a project, there are basically three environments, development environment, test environment, formal environment, these three environments need to configure three different resources, such as pictures, interface address, buried point, Baidu statistics and so on.

So how do we get the environment variable in vite.config.js when packaging? First, change the package.json scripts property to look like this:

scripts: {
	"dev": "vite --mode development"."build:beta": "vite build --mode beta"."build:release": "vite build --mode release"."serve": "vite preview"
}
Copy the code

–mode = environment variable; –mode = environment variable Official, you can get the value of this variable in the page.

We print something like this in vite.config.js:

console.log('process:::env', process.argv)
Copy the code

Rerun NPM run dev as shown below:

The last parameter is the environment variable that we set. So we can obtain the environment variable by:

const env = process.argv[process.argv.length - 1]
Copy the code

We can configure the path prefix of the static resources in index.html in ite. Config.js. The changes are as follows:

.const env = process.argv[process.argv.length - 1]
const base = config[env]
...
export default defineConfig({
	base: base.cdn
})
Copy the code

In the config directory of the root directory, add the index.js file with the following content:

export default {
  development: {
    cdn: '/'.apiBaseUrl: '/api' // The development environment interface request is used for proxy configuration
  },
  beta: {
    cdn: '//s.xxx.com/vite-react-app/beta'.// Test environment CDN path
    apiBaseUrl: '//www.beta.xxx.com/v1' // Test environment interface address
  },
  release: {
    cdn: '//s.xxx.com/vite-react-app/release'.// The official environment CDN path
    apiBaseUrl: '//www.xxx.com/v1' // The official environment interface address}}Copy the code

Let’s make a test package and run the following command:

npm run build:beta
Copy the code

The results are as follows:The same can be said for birds in formal environments.

So when we run the code, how do we get the environment variable? The answer is import.meta. Env. Print it out in Index/index. JSX:

import React from 'react'
import { Button } from 'antd'

export default function Index() {
  console.log('import.meta.env'.import.meta.env)
  return <div>
    <Button type='primary'>Index</Button>
  </div>
}
Copy the code

Returns an object with the parameters in it. In this case, we need the parameters for the MODE property, which is the current environment variable.

Encapsulate AXIOS twice

When developing the project, the server will provide us with the test interface and the formal interface, here we need to configure the corresponding variables to dynamically obtain the request address. First let’s install axios and QS:

npm i axios qs -S
Copy the code

Then, under SRC, create a new utils directory dedicated to the various tool methods. Create index.js under utils and add the following code:

import axios from 'axios'
import { message } from 'antd'
import { stringify } from 'qs'
import config from '.. /.. /config'

const MODE = import.meta.env.MODE // Environment variables

const getRequest = (method) = > {
  return (url, data, options = {}) = > {
    let base = config[MODE] // Get the attribute value corresponding to the environment variable
    return axios({
      baseURL: base.apiBaseUrl, // Request the domain name addressmethod, url, ... (method ==='POST'
        ? {
            data: options.string ? stringify(data) : data,
          }
        : {}),
      params: method === 'GET' ? data : options.params,
      headers: {
        'X-Requested-With': 'XMLHttpRequest'.'Content-Type': options.string
          ? 'application/x-www-form-urlencoded'
          : 'application/json'. options.headers, },withCredentials: true,
    })
      .then((res) = > {
        if (typeofres.data ! = ='object') {
          console.error('Data format response error :', res.data)
          message.error('Crowded ahead, please refresh and try again')
          return Promise.reject(res)
        }

        if (res.data.errcode) {
          if (res.data.errcode == 401) {
            window.location.href = 'login' // When the login fails, the login page is displayed
            return
          }
          // With the silent option, no error is displayed
          if(res.data.message && ! options.silent) message.error(res.data.message)return Promise.reject(res.data)
        }

        return res.data
      })
      .catch((err) = > {
        message.error('System error'.2)
        return Promise.reject(err)
      })
  }
}

export const get = getRequest('GET')

export const post = getRequest('POST')
Copy the code

The value of the apiBaseUrl variable can be obtained by using the config[MODE] command to obtain the values of the development, test, and official attributes.

To add the request proxy for the development environment as well, let’s open v.config.js and add the following properties:

.export default defineConfig({
	...
	server: {
    port: 3001.// The port on which the development environment started
    proxy: {
      '/api': {
        // When the/API path is encountered, convert it to the target value. Here we write the request address for the new bee store for testing
        target: 'http://47.99.134.126:28019/api/v1'.changeOrigin: true.rewrite: path= > path.replace(/^\/api/.' ') // Overwrite/API to null}}}})Copy the code

To test whether the interface request succeeded, we add the following code in Index/index. JSX:

import React, { useEffect } from 'react'
import { Button } from 'antd'
import { get } from '.. /.. /utils'

export default function Index() {
  useEffect(() = > {
    get('/index-infos').then(() = >{})}, [])return <div>
    <Button type='primary'>Index</Button>
  </div>
}
Copy the code

Restart the project and the result looks like this:

Resolve. alias Alias setting

Like most configuration items, the alias configuration is also in vite.config.js. We open it and add the following code:

export default defineConfig({
	...
  resolve: {
    alias: {
      '~': path.resolve(__dirname, '/'), / / root path
      The '@': path.resolve(__dirname, 'src') / / SRC path}}... })Copy the code

After the configuration, let’s rewrite some of the paths in the above code as follows:

// router/index.js
import Index from '@/container/Index'
import About from '@/container/About'

// utils/index.js
import config from '~/config'

// App.jsx
import routes from '@/router'
Copy the code

Convenient and brief, the follow-up can continue to add some paths, fewer words, improve the development efficiency.

conclusion

This is the end of this article. What? You also need TS, CSS Module, Eslint, don’t make a fool of yourself, go to the warehouse to download the code, play slowly, I am writing vomit, please like ah! After 500 likes, I will add another Vite + Vue + Element-plus. Yo-yo

Previous good article recommendation

In the face of the interview, you have to understand the prototype and prototype chain likes 👍 495

Vue 3 and Webpack 5 are coming, manually built knowledge of the update is up to 👍 479

From another point of view, web page performance optimization points like 👍 173

Hello, tell me about your understanding of front-end routing

Before I had no choice, now I just want to use array.prototype.reduce 👍 554

The ubiquitous publish/subscribe model – this time be sure to like 👍 554

Talk about JSX and virtual DOM