「ゼロからVue3を」Vue3+vite+ElementPlusで環境構築

最終更新日2022年4月16日 午後

概要

今回はVue.jsのデフォルトバージョンになる「Vue3」を用いて、ゼロから一つの管理システムを作ると思います。
UIフレームワークについて、Vue3バージョンのVuetifyはリリースされてないから、ElementPlusにします。
Typescriptは「型宣言」なので、エラーやバグを未然に防止できるし、開発効率も上がります。
viteの起動が非常に早い~

環境

Node.jsとnpmバージョン

1
2
node v14.17.1
npm 6.14.13

create viteでプロジェクト作成

参考:公式サイト
npm -vでnpmのバージョンを確認する
下記のコマンドで、プロジェクト作成

1
2
3
4
5
# npm 6.x 
# npm create viteバージョン プロジェクト名 --template テンプレート
npm create vite@latest mtool --template vue-ts
# npm 7+ は追加で 2 つのダッシュが必要:
npm create vite@latest my-vue-app -- --template vue

プロジェクトのmtoolが作成されました。
下記はコマンドを実行した結果

1
2
3
4
5
6
npx: installed 6 in 3.147s
Scaffolding project in C:\files\workspaces\vue3\mtool...
Done. Now run:
cd mtool
npm install
npm run dev

次のコマンドにより初期化

1
2
3
4
5
6
7
8
9
10
11
12
13
# プロジェクトのフォルダーに移動する
cd mtool
# ライブラリをインストールする
npm install
# Vueを動かす
npm run dev
# npm run devの結果、ブラウザーにURLを開く
vite v2.9.1 dev server running at:

> Local: http://localhost:3000/
> Network: use `--host` to expose

ready in 227ms.

ElementPlus

上記の手順により、Vue3が起動しました。
次はUIフレームワークのElementPlusを導入する。
参考:公式サイト

インストール

1
2
# cd <プロジェクトのフォルダー>
npm install element-plus --save

フルインポート

バンドルサイズをあまり気にしない場合は、フルインポートを使用する方が便利です。

参考:公式サイト

配置(オートインポート)

先ずは二つのプラグインをインストールする。

1
2
# `components.d.ts`が作成されて、自動インポートのコンポーネントはこちらに宣言されます。
npm install -D unplugin-vue-components unplugin-auto-import

次はvite.config.tsを編集する

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default {
plugins: [
// ...
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
],
}

使い方

1
2
3
4
5
<template>
<el-button type="primary">
ボタンです
</el-button>
</template>

icon

インストールと配置

ElementPlusのiconとオートインポートのプラグインをインストールする

1
2
npm install @element-plus/icons-vue
npm i -D unplugin-icons

vite.config.tsを編集する

1
2
3
4
5
6
7
8
import Icons from 'unplugin-icons/vite'

export default defineConfig({
plugins: [
// ...
Icons({ compiler: 'vue3' }),
],
})

使い方

1
2
3
4
5
6
7
8
<template>
<el-button type="primary">
<el-icon size="22" color="#ff0000"><Expand /></el-icon>test
</el-button>
</template>
<script setup lang="ts">
import { Expand } from '@element-plus/icons-vue'
</script>

結果

次回の投稿

vue-routerについて


コンテンツは、特に記載されていない限り、CC BY-SA 4.0のもとで利用可能です。