[vue3+vite+tsx]プロジェクト構築の詳細プロセス

目次

  1. 環境要件
  2. Vite + Vue3 ビルドの初期化
  3. ルーティング ルーターのインストールと構成
  4. tsx サポートを構成する
  5. 以下のインストールと使用
  6. スタイルの統一的な導入
  7. ElementUIのインストールと使用
  8. vite 設定パスのエイリアス
  9. i18n 構成多言語
  10. システムのレイアウトUIを設計する
  11. デザインメニューバー + 権限制御
  12. デザインAPIディレクトリ
  13. モックを設定する
  14. 機能ページの書き込み

1. 環境要件

  • ノード: Node.js バージョン >= 12.0.0、現在使用されているバージョン: v14.16.0
  • パッケージ管理ツール: npm/yarn、現在糸を使用: v1.22.10
  • エディタ: VSCode

2. Vite + Vue3 ビルドの初期化

  1. vite をグローバルにインストールする
yarn global add vite


# 安装vite+vue3.0项目,Vite 需要 Node.js 版本 >= 12.0.0。
D:/
# 基于vite搭建项目,项目名:rbac-manage,前端框架使用vue,开发语言:typescript
yarn create vite
# √ Project name: ... rbac-manage
# √ Select a framework: » vue
# √ Select a variant: » vue-ts

# 切换工作目录到rbac-manage,
cd rbac-manage
# 下载项目运行的前端依赖模块
  1. vite に基づいてプロジェクトをビルドします。プロジェクト名: rbac-manage、フロントエンド フレームワークは vue3 を使用、開発言語: TypeScript
yarn create vite

# √ Project name: ... rbac-manage
# √ Select a framework: » vue
# √ Select a variant: » vue-ts
  1. スタートアッププロジェクト
# 切换工作目录到rbac-manage
cd rbac-manage
# 下载项目运行的前端依赖模块
yarn
# 启动测试服务器,运行vue项目
yarn dev

これまでのところ、Vite によってビルドされた Vue3 プロジェクトがビルドされ、TypeScript 構文をサポートしています。

3. ルーターのインストールと設定

  1. vue-router 4.x をインストールする
yarn add vue-router@next
  1. ルーティングモジュールを構成する

作成src/router/index.ts、コード:

import {
    
    createRouter, Router, createWebHistory, RouteRecordRaw} from 'vue-router'

// 路由列表
const routes:Array<RouteRecordRaw> = [
  // 省略,见项目src/router/index.ts具体代码
]

const router:Router = createRouter({
    
    
  // history, 指定路由的模式
  history: createWebHistory(),
  // 路由列表
  routes,
});

export default router

プロジェクトのモジュール分割によると、設計プロジェクトのディレクトリとプロジェクトのルーティングは次のとおりです。

  • 以下に示すように、ディレクトリを作成しsrc/views、ログイン ディレクトリ、メンバー ディレクトリ、デバイス ディレクトリ、オペレータ ディレクトリ、ポイントグループ ディレクトリ、シナリオ ディレクトリ、wbs ディレクトリを追加し、Index.vue ファイルを各モジュールのエントリ ファイルとして各ディレクトリに追加します。
  • src/router/index.ts次のように、プロジェクト ルーティング内のルーターを更新します。
const routes: Array<RouteRecordRaw> = [
  {
    
    
    name: "index",
    path: "/",
    redirect: "/member",
  },
  {
    
    
    name: "Login",
    path: "/login",
    component: () => import("../views/login/Index.vue"),
  },
  {
    
    
    name: "Member",
    path: "/member",
    component: () => import("../views/member/Index.vue"),
  },
  {
    
    
    name: "Device",
    path: "/device",
    component: () => import("../views/device/Index.vue"),
  },
  {
    
    
    name: "Operator",
    path: "/operator",
    component: () => import("../views/operator/Index.vue"),
  },
  {
    
    
    name: "PointGroup",
    path: "/point-group",
    component: () => import("../views/point-group/Index.vue"),
  },
  {
    
    
    name: "Scenario",
    path: "/scenario",
    component: () => import("../views/scenario/Index.vue"),
  },
  {
    
    
    name: "Wbs",
    path: "/wbs",
    component: () => import("../views/wbs/Index.vue"),
  },
];
  • router.ts をプロジェクトに導入します

ファイル内でsrc/main.ts、ルーターオブジェクトをプロジェクトに登録します

import {
    
     createApp } from "vue";
import App from "./App.vue";
import router from "./router";

createApp(App).use(router).mount("#app");

src/App.vueコンポーネントに、表示ルートに対応するコンテンツを追加します。

<template>
  <router-view />
</template>

<script setup lang="ts"></script>

この時点で、プロジェクト ルーティング スイッチの構築は完了です。

4. tsx サポートを構成する

ドキュメント: https://cn.vitejs.dev/guide/features.html#jsx

  1. プラグインをインストールする
yarn add -D @vitejs/plugin-vue-jsx
  1. 構成vite.config.ts
import {
    
     defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";

// https://vitejs.dev/config/
export default defineConfig({
    
    
  plugins: [vue(), vueJsx({
    
    })],
});
  1. tsconfig.jsonを構成する
{
    
    
  "compilerOptions": {
    
    
    "jsx": "preserve",
    "jsxFactory": "h",
    "jsxFragmentFactory": "Fragment"
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}
  1. テストvue3 + tsx

コンポーネント ディレクトリに TestDemo.tsx ファイルを作成し、ページ内でそれを参照して、tsx ファイルが正常に解析されるかどうかをテストします。

import {
    
     FunctionalComponent as FC, defineComponent, reactive, onMounted } from 'vue';

// 无状态组件
const FcNode: FC<{
    
     data: number }> = ({
    
     data }) => {
    
    
  return (
    <>
      <hr />
      <div>子组件:
        {
    
    data < 10 ? <span>{
    
    data}</span> : <h1>{
    
    data}</h1>}
      </div>
    </>
  )
};

// 状态组件需要使用 defineComponent
export default defineComponent({
    
    
  name: 'TsxDemo',
  setup() {
    
    
    const data = reactive({
    
     count: 0 });

    onMounted(() => {
    
    
      data.count = 5;
    });

    const clickHandler = () => data.count++

    return () => (
      <>
        <span style={
    
    {
    
     marginRight: '10px' }}>{
    
     data.count }</span>
        <button onClick={
    
    clickHandler}>+</button>
        <FcNode data={
    
    data.count}/>
      </>
    )
  }
})

ここまででtsxの設定は完了です。

5.lessのインストールと使用

ドキュメント: https://cn.vitejs.dev/guide/features.html#css

  1. インストール
yarn add less

Vite は、.scss、.sass、.less、.styl、.stylus ファイルのサポートを組み込みで提供します。これらのファイルに特定の vite プラグインをインストールする必要はありません。プリプロセッサの依存関係自体をインストールするだけで、プロジェクト内で直接使用できます。

  1. Less が機能するかどうかと CSS モジュールをテストする

Vue 開発では、コンポーネント間のスタイル汚染を防ぐために、通常、コンポーネントに対してローカルで有効なスタイルを設定する必要があります。

  • .vue 単一ファイルでは次を使用します。
<style scoped lang="less">
.header {
  font-size: 36px;
  font-weight: bold;
}
</style>
  • .tsx ファイルで使用する: スタイル ファイルの接尾辞の前に .module (index.module.less) を追加し、スタイルを tsx にインポートして使用します。
import classes from "./tsx.module.less"

const FcNode: FC<{ data: number }> = ({ data }) => {
  return (
    <>
      <hr />
      <div class={classes['son-header']}>子组件:
        {data < 10 ? <span>{data}</span> : <h1>{data}</h1>}
      </div>
    </>
  )
};

これまでのところ、less 構文はプロジェクト内で通常どおり使用できます。

6. スタイルの統一導入

  • src/styles/reset.lessデフォルトのスタイルをクリアしてファイルを作成します。
  • 統一されたスタイル管理としてファイルを作成するsrc/styles/index.lessと、いくつかのグローバル スタイルを同時に記述することができます。
@import "./reset.less";

/* Global css */
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  width: 100%;
  height: 100%;
}
  • main.ts紹介されましたsrc/styles/index.less

7. ElementUIのインストールと使用方法

ドキュメント: https://element-plus.org/zh-CN/

  1. インストール
yarn add element-plus
  1. 必要に応じて ElementUI をプラグインの形式で導入します
  • scr/plugins/element-plus.tsButton コンポーネントの導入を例として、プラグインを作成します。
import {
    
     createApp } from "vue";
// 引入样式
import "element-plus/dist/index.css";
// 按需引入组件
import {
    
     ElButton, ElMessage } from "element-plus";

export default function loadComponent(app: ReturnType<typeof createApp>) {
    
    
  // 注册组件
  app.use(ElButton);
  app.config.globalProperties.$message = ElMessage;
}
  • scr/plugins/index.tsプラグインの統合導入を容易にするファイルを作成します。
import {
    
     createApp } from 'vue'
import elementPlugin from "./element-plus";

/**
 * @description 加载所有 Plugins
 * @param  {ReturnType<typeofcreateApp>} app 整个应用的实例
 */
export function loadAllPlugins(app: ReturnType<typeof createApp>) {
    
    
  elementPlugin(app)
}
  • src/main.tsファイル内のすべてのプラグインをロードします
import {
    
     createApp } from "vue";
import App from "./App.vue";
import {
    
     loadAllPlugins } from "./plugins";
import router from "./router";

// 应用实例
const app = createApp(App)

// 加载所有插件
loadAllPlugins(app)

app.use(router).mount("#app");
  • ページで次を使用します。
<template>
  <div class="header">
    <el-button>my button</el-button>
  </div>
</template>

8. vite 設定パスのエイリアス

コードの再利用を容易にするために、カスタム構成パスのエイリアスは @ に設定されます。具体的な構成は次のとおりです。

  • vite.config.tsファイル内で設定します。
export default defineConfig({
    
    
  resolve: {
    
    
    alias: {
    
    
      "@": path.resolve(__dirname, "src"),
    },
  }
});
  • tsconfig.json設定する
"compilerOptions": {
    
    
    "paths": {
    
    
        "@/*": ["./src/*"]
    }
},
  • ページ内で引用する
import TsxDemo from "@/components/TsxDemo"

(追記: 設定が完了したら、次のプロジェクトを再起動してください)

9. i18n 設定の多言語化

  1. vue-i18n をインストールする
yarn add vue-i18n@next
  1. 多言語src/locale/zh-cn.ts言語ファイル、src/locale/ja.ts言語ファイルを作成し、src/locale/index言語ファイルを均一にインポートするためのファイルを作成します。
import Keys from "@/constant/key";
import {
    
     createI18n } from "vue-i18n";
import localeLangJa from "./ja";
import localeLangZhCn from "./zh-cn";

const messages = {
    
    
  "zh-cn": {
    
    
    ...localeLangZhCn,
  },
  ja: {
    
    
    ...localeLangJa,
  },
};

export const getLocale = () => {
    
    
  // 先寻找缓存里的lang
  const localLanguage = window.localStorage.getItem(Keys.languageKey);
  if (localLanguage) {
    
    
    return localLanguage;
  }
  // 如果缓存没有设置lang,根据所在地查询配置并显示对应lang
  const language = navigator.language.toLowerCase();
  const locales = Object.keys(messages);
  for (const locale of locales) {
    
    
    if (language.indexOf(locale) > -1) {
    
    
      return locale;
    }
  }

  // 没有对应的语言配置,显示默认语言
  return "ja";
};

const i18n = createI18n({
    
    
  // 设置地区
  locale: getLocale(),
  // 设置地区信息
  messages,
});

export default i18n;
  1. ElementUIコンポーネントライブラリと組み合わせて多言語を構成

グローバル多言語構成を App.vue ファイルに挿入します。

<template>
  <el-config-provider :locale="locale">
    <router-view />
  </el-config-provider>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { getLocale } from "@/locale"

/** 配置默认语言 */
const locale = ref<string>(getLocale())
</script>
  1. 使用構文: $t("key")

10. システムのレイアウト UI を設計する

要件に応じて、均一に処理する必要がある要素や一部の操作の再利用を容易にするために、基本的なレイアウト ページ レイアウトが必要です。

おすすめ

転載: blog.csdn.net/jexxx/article/details/128680853