vue3+vite+ts configuration

1. src alias configuration

  • Download pathmodule

npm i @types/path

  • vue.config.tsConfigure the alias path in
// vite.config.ts
import {
    
    defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
export default defineConfig({
    
    
    plugins: [vue()],
    resolve: {
    
    
        alias: {
    
    
            "@": path.resolve("./src") // 相对路径别名配置,使用 @ 代替 src
        }
    }
})

existTypeScripe配置编译命令

// tsconfig.json
{
    
    
  "compilerOptions": {
    
    
    "baseUrl": "./", // 解析非相对模块的基地址,默认是当前目录
    "paths": {
    
     //路径映射,相对于baseUrl
      "@/*": ["src/*"] 
    }
  }
}

2. svg configuration

  • Install dependencies
npm install vite-plugin-svg-icons -D
  • vite.config.tsConfigure the plugin in
import {
    
     createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {
    
    
  return {
    
    
    plugins: [
      createSvgIconsPlugin({
    
    
        // Specify the icon folder to be cached
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        // Specify symbolId format
        symbolId: 'icon-[dir]-[name]',
      }),
    ],
  }
}
  • Import into main
import 'virtual:svg-icons-register'
  • use
  • 注意点The folder name is optional, please refer to the specific storage path and plug-in configuration path.
    <svg aria-hidden="true">
      <!-- #icon-文件夹名称-图片名称 -->
      <use href="#icon-login-eye-off" />
    </svg>

2.1 Encapsulating svg global components

  • src/componentsCreate a SvgIconcomponent in the directory
<template>
  <div>
    <svg :style="{ width: width, height: height }">
      <use :xlink:href="prefix + name" :fill="color"></use>
    </svg>
  </div>
</template>

<script setup lang="ts">
defineProps({
    
    
  //xlink:href属性值的前缀
  prefix: {
    
    
    type: String,
    default: '#icon-'
  },
  //svg矢量图的名字
  name: String,
  //svg图标的颜色
  color: {
    
    
    type: String,
    default: ""
  },
  //svg宽度
  width: {
    
    
    type: String,
    default: '16px'
  },
  //svg高度
  height: {
    
    
    type: String,
    default: '16px'
  }

})
</script>
<style scoped></style>
  • Create a file in the src folder index.ts: used to register all global components in the components folder
import SvgIcon from './SvgIcon/index.vue';
import type {
    
     App, Component } from 'vue';
const components: {
    
     [name: string]: Component } = {
    
     SvgIcon };
export default {
    
    
    install(app: App) {
    
    
        Object.keys(components).forEach((key: string) => {
    
    
            app.component(key, components[key]);
        })
    }
}
  • Declare the type of global component. types/components.d.ts
    For specific configuration, please refer to element-plus.
// 设置全局组件类型
import SvgIcon from '@/components/SvgIcon.vue'
// 2. 声明 vue 类型模块
declare module 'vue' {
    
    
  // 3. 给 vue  添加全局组件类型,interface 和之前的合并
  interface GlobalComponents {
    
    
    // 4. 定义具体组件类型,typeof 获取到组件实例类型
    // typeof 作用是得到对应的TS类型
    SvgIcon: typeof SvgIcon
  }
}
  • Introduce files in the entry file and install custom plug-ins src/index.tsthrough methodsapp.use
import gloablComponent from './components/index';
app.use(gloablComponent);

3. Integrate scss and css to complete theme customization

First of all, $both and :rootare methods for defining CSS variables, but they have some differences.

  • :rootSelectors are used to define global CSS variables, usually used in the root element (ie, HTML element). For example:
:root {
    
    
  --primary-color: #007bff;
}

body{
    
    
color:var(--primary-color)
}
  • This defines a global variable named --primary-color that can be used throughout the page.

  • And $is Sassor @is Lesssyntax for defining variables in CSS preprocessors. In Sass, you can use $the notation to define variables, for example:

$primary-color: #007bff;
body {
    
    
  color: $primary-color;
}
  • This defines a $primary-colorvariable named and applies it to the color attribute in the body element.
  • In general, :rootit is used to define global CSS variables, and $is used to define variables in the preprocessor. Both work similarly, but use slightly different methods.

3.1 Configure scss in vite

When you use it in the index.scss global style file, $ 变量an error will be reported. Therefore, global variables need to be introduced into the project $.

$base-menu-background: #001529;
::-webkit-scrollbar-track {
    
    
    background: $base-menu-background;
}
  • The file configuration is vite.config.tsas follows:
export default defineConfig((config) => {
    
    
	css: {
    
    
      preprocessorOptions: {
    
    
        scss: {
    
    
        // 用于解析$定义的样式
          javascriptEnabled: true,
          additionalData: '@import "./src/styles/variable.scss";',
        },
      },
    },
	}
}

4. Environment variable configuration

During the project development process, there will be three stages: development environment, test environment and production environment (ie formal environment). The status of requests (such as interface addresses, etc.) at different stages is different. Manually switching the interface address is quite tedious and error-prone. So the need for environment variable configuration emerged. We only need to do simple configuration and leave the work of switching environment states to the code.

Development environment (development)
developers work on their own dev branch. When development reaches a certain level, colleagues will merge the code and conduct joint debugging.

Testing environment (testing)
is the environment where test colleagues work. It is usually deployed by the test colleagues themselves and then tested in this environment.

The production environment (production)
refers to the environment used for formal operation and delivery in software development. The production environment generally turns off error reporting and turns on error logs. (Environment officially provided to customers.)

Note: Generally, one environment corresponds to one server, and some companies' development and testing environments are one server! ! !

  • Add files for development, production and test environments to the project root directory respectively!
.env.development
.env.production
.env.test

development environment

# 变量必须以 VITE_ 为前缀才能暴露给外部读取
NODE_ENV = 'development'
VITE_APP_TITLE = '项目的标题'
VITE_APP_BASE_API = '/dev-api'

Production Environment

NODE_ENV = 'production'
VITE_APP_TITLE = '项目标题'
VITE_APP_BASE_API = '/prod-api'

test environment

# 变量必须以 VITE_ 为前缀才能暴露给外部读取
NODE_ENV = 'test'
VITE_APP_TITLE = '项目的标题'
VITE_APP_BASE_API = '/test-api'
  • package.jsonRun command in configuration
 "scripts": {
    
    
    "dev": "vite --open",
    "build:test": "vue-tsc && vite build --mode test",
    "build:pro": "vue-tsc && vite build --mode production",
    "preview": "vite preview"
  },

index.htmlused inVITE_APP_TITLE

  • Install plugin
npm add vite-plugin-html -D

vite.config.tsConfiguration

import {
    
     createHtmlPlugin } from 'vite-plugin-html'
plugins: [
  createHtmlPlugin()
]

index.html <%=环境变量名%> Get value

  <head>
    <meta charset="UTF-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title><%=VITE_APP_TITLE%></title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script

5. Mobile terminal adaptation

  • Use to vwcomplete mobile terminal adaptation
    and install the module
npm install postcss-px-to-viewport -D

Configuration: postcss.config.ts

module.exports = {
    
    
  plugins: {
    
    
    'postcss-px-to-viewport': {
    
    
      // 设备宽度375计算vw的值
      viewportWidth: 375,
    },
  },
};

6. Automatically load on demand

  • Install
npm i unplugin-vue-components -D
  • use
import Components from 'unplugin-vue-components/vite'
  plugins: [
    // 解析单文件组件的插件
    vue(),
    // 自动导入的插件,解析器可以是 vant element and-vue 
    Components({
    
    
      dts: false,
      // 原因:Toast Confirm 这类组件的样式还是需要单独引入,样式全局引入了,关闭自动引入
      resolvers: [VantResolver({
    
     importStyle: false })]
    })
  ],
  • antd use
npm i ant-design-vue@next
import Components from 'unplugin-vue-components/vite'
import {
    
     AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
    
    
  plugins: [
    .......其它plugins配置
    Components({
    
    
      resolvers: [
        AntDesignVueResolver(),
      ]
    }),
  ........其它plugins配置
  ]
})

Detailed usage reference link

7. mock configuration

  • Install
pnpm i vite-plugin-mock mockjs -D
  • vite.config.tsEnable plugin in configuration file
import {
    
     viteMockServe } from 'vite-plugin-mock'
plugins: [
    viteMockServe({
    
    
     // mockPath 默认不配置地洞找src同级的目录
      mockPath: './src/mock',
      localEnabled: true
    })
]
//用户信息数据
function createUserList() {
    
    
    return [
        {
    
    
            userId: 1,
            avatar:
                'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            username: 'admin',
            password: '111111',
            desc: '平台管理员',
            roles: ['平台管理员'],
            buttons: ['cuser.detail'],
            routes: ['home'],
            token: 'Admin Token',
        },
        {
    
    
            userId: 2,
            avatar:
                'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            username: 'system',
            password: '111111',
            desc: '系统管理员',
            roles: ['系统管理员'],
            buttons: ['cuser.detail', 'cuser.user'],
            routes: ['home'],
            token: 'System Token',
        },
    ]
}

export default [
    // 用户登录接口
    {
    
    
        url: '/api/user/login',//请求地址
        method: 'post',//请求方式
        response: ({
     
      body }) => {
    
    
            //获取请求体携带过来的用户名与密码
            const {
    
     username, password } = body;
            //调用获取用户信息函数,用于判断是否有此用户
            const checkUser = createUserList().find(
                (item) => item.username === username && item.password === password,
            )
            //没有用户返回失败信息
            if (!checkUser) {
    
    
                return {
    
     code: 201, data: {
    
     message: '账号或者密码不正确' } }
            }
            //如果有返回成功信息
            const {
    
     token } = checkUser
            return {
    
     code: 200, data: {
    
     token } }
        },
    },
    // 获取用户信息
    {
    
    
        url: '/api/user/info',
        method: 'get',
        response: (request) => {
    
    
            //获取请求头携带token
            const token = request.headers.token;
            //查看用户信息是否包含有次token用户
            const checkUser = createUserList().find((item) => item.token === token)
            //没有返回失败的信息
            if (!checkUser) {
    
    
                return {
    
     code: 201, data: {
    
     message: '获取用户信息失败' } }
            }
            //如果有返回成功信息
            return {
    
     code: 200, data: {
    
    checkUser} }
        },
    },
]

Mock detailed syntax reference link

Guess you like

Origin blog.csdn.net/weixin_46104934/article/details/131360786