A-Frame の開発で Vite を導入するメモです。
背景
A-Frame で開発していると結構楽しいんですが、外部 API のやりとりや画面遷移やオブジェクトが増えてくると管理が大変になってくるので、テストサーバーや JavaScript のバンドルなど Vite の恩恵が欲しくなってくるので、やってみました。
Vite を vanilla で構築
こちらにある通り、素の JavaScript プロジェクトの vanilla で構築します。
npm create vite@latest my-aframe-app -- --template vanilla
私の場合は npm なのでこちらでプロジェクトフォルダの最上部で構築開始。
初期ファイルの整理
いろいろ準備されているのでシンプルにします。
main.js と index.html を残します。
A-Frame 環境を構築
Introduction – A-Frame を参考に、A-Frame 環境を構築します。
index.html の中身です。a-box に id=”box” を指定して、下部の script タグで main.js を呼んでます。
<html> <head> <script src="https://aframe.io/releases/1.6.0/aframe.min.js"></script> </head> <body> <a-scene> <a-camera> <a-cursor></a-cursor> </a-camera> <a-box id="box" position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9"></a-box> <a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere> <a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D"></a-cylinder> <a-plane position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4"></a-plane> <a-sky color="#ECECEC"></a-sky> </a-scene> <script type="module" src="/main.js"></script> </body> </html>
main.js の中身です。box をクリックすると青く変わる仕組みです。
const el = document.querySelector('#box'); el.addEventListener('click',function (evt) { evt.currentTarget.setAttribute('material', 'color', 'blue'); console.log('click!'); });
これで準備は完了です。
フォルダ移動とインストール
cd my-aframe-app
フォルダを移動して、
npm install
で、一式インストールします。
動かしてみる
では動かしてみましょう。
npm run dev
でテストサーバーを起動します。
無事表示されました。
画面を動かしてカーソルに box を合わせて、マウスクリックします。
クリックすると色が変わりました!
コンソールでも console.log が出力されています。
これで A-Frame でも Vite の仕組みが使えて開発がしやすくなります!