vue3+vite+ts 構成

1. srcエイリアスの設定

  • ダウンロードpathモジュール

npm i @types/path

  • vue.config.tsエイリアス パスを設定します
// 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
        }
    }
})

存在するTypeScripe配置编译命令

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

2.SVG設定

  • 依存関係をインストールする
npm install vite-plugin-svg-icons -D
  • vite.config.tsプラグインを設定します
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 'virtual:svg-icons-register'
  • 使用
  • 注意点フォルダー名はオプションです。特定のストレージ パスとプラグイン構成パスを参照してください。
    <svg aria-hidden="true">
      <!-- #icon-文件夹名称-图片名称 -->
      <use href="#icon-login-eye-off" />
    </svg>

2.1 svg グローバル コンポーネントのカプセル化

  • ディレクトリにコンポーネントsrc/componentsを作成するSvgIcon
<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>
  • src フォルダーにファイルを作成しますindex.ts。すべてのグローバル コンポーネントをコンポーネント フォルダーに登録するために使用されます。
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]);
        })
    }
}
  • グローバルコンポーネントのタイプを宣言します。types/components.d.ts
    具体的な設定については、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
  }
}
  • エントリファイルにファイルを導入し、メソッドsrc/index.tsを通じてapp.useカスタムプラグインをインストールします
import gloablComponent from './components/index';
app.use(gloablComponent);

3. scss と css を統合してテーマのカスタマイズを完了する

まず、$と はどちらも:rootCSS 変数を定義するメソッドですが、いくつかの違いがあります。

  • :rootセレクターは、グローバル CSS 変数を定義するために使用され、通常はルート要素 (つまり、HTML 要素) で使用されます。例えば:
:root {
    
    
  --primary-color: #007bff;
}

body{
    
    
color:var(--primary-color)
}
  • これにより、ページ全体で使用できる --primary-color という名前のグローバル変数が定義されます。

  • CSS プリプロセッサで変数を定義するためのAnd $isSassまたは@is構文。Lessでは、次のような表記法を使用して変数を定義Sassできます。 $

$primary-color: #007bff;
body {
    
    
  color: $primary-color;
}
  • これにより、$primary-colorという名前の変数が定義され、それが body 要素の color 属性に適用されます。
  • 一般に、:rootこれはグローバル CSS 変数を定義するために使用され、 $プリプロセッサで変数を定義するために使用されます。どちらも同様に機能しますが、使用する方法が少し異なります。

3.1 vite で scss を構成する

グローバルスタイルファイルindex.scss内で使用すると$ 变量エラーが報告されるため、プロジェクトにグローバル変数を導入する必要があります$

$base-menu-background: #001529;
::-webkit-scrollbar-track {
    
    
    background: $base-menu-background;
}
  • ファイル構成は以下のとおりですvite.config.ts
export default defineConfig((config) => {
    
    
	css: {
    
    
      preprocessorOptions: {
    
    
        scss: {
    
    
        // 用于解析$定义的样式
          javascriptEnabled: true,
          additionalData: '@import "./src/styles/variable.scss";',
        },
      },
    },
	}
}

4. 環境変数の設定

プロジェクトの開発プロセスには、開発環境、テスト環境、本番環境 (正式な環境) の 3 つの段階があります。リクエストのステータス (インターフェイス アドレスなど) は各段階で異なるため、インターフェイス アドレスを手動で切り替えるのは非常に面倒で、エラーが発生しやすくなります。そこで、環境変数を設定する必要性が生じ、簡単な設定を行うだけで済み、環境の状態を切り替える作業はコードに任せることができます。

開発環境(開発)
の開発者は自分のdevブランチで作業を行い、開発が一定のレベルに達すると同僚がコードをマージして共同デバッグを行います。

テスト環境 (テスト)
は、テスト仲間が作業する環境で、通常はテスト仲間自身によって展開され、この環境でテストされます。

実稼働環境 (本番) とは、
ソフトウェア開発における正式な運用と配信に使用される環境を指します。実稼働環境では、通常、エラー報告がオフになり、エラー ログがオンになります。(お客様に正式に提供される環境です。)

注: 通常、1 つの環境は 1 つのサーバーに対応し、一部の企業の開発およびテスト環境は 1 つのサーバーです。

  • 開発環境、実稼働環境、テスト環境のファイルをそれぞれプロジェクトのルート ディレクトリに追加します。
.env.development
.env.production
.env.test

開発環境

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

本番環境

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

テスト環境

# 变量必须以 VITE_ 为前缀才能暴露给外部读取
NODE_ENV = 'test'
VITE_APP_TITLE = '项目的标题'
VITE_APP_BASE_API = '/test-api'
  • 構成でpackage.jsonコマンドを実行する
 "scripts": {
    
    
    "dev": "vite --open",
    "build:test": "vue-tsc && vite build --mode test",
    "build:pro": "vue-tsc && vite build --mode production",
    "preview": "vite preview"
  },

index.htmlで使われるVITE_APP_TITLE

  • プラグインのインストール
npm add vite-plugin-html -D

vite.config.ts構成

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

index.html <%=环境变量名%> 値の取得

  <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. モバイル端末への適応

  • vwモバイル端末の適応を完了し
    、モジュールをインストールするために使用します
npm install postcss-px-to-viewport -D

構成: postcss.config.ts

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

6. オンデマンドで自動的にロードする

  • インストール
npm i unplugin-vue-components -D
  • 使用
import Components from 'unplugin-vue-components/vite'
  plugins: [
    // 解析单文件组件的插件
    vue(),
    // 自动导入的插件,解析器可以是 vant element and-vue 
    Components({
    
    
      dts: false,
      // 原因:Toast Confirm 这类组件的样式还是需要单独引入,样式全局引入了,关闭自动引入
      resolvers: [VantResolver({
    
     importStyle: false })]
    })
  ],
  • 使用する
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配置
  ]
})

詳しい使い方参考リンク

7. モック構成

  • インストール
pnpm i vite-plugin-mock mockjs -D
  • 設定ファイルでvite.config.tsプラグインを有効にする
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} }
        },
    },
]

モックの詳細な構文リファレンスのリンク

おすすめ

転載: blog.csdn.net/weixin_46104934/article/details/131360786