9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Cesium.js環境構築(Viteを使う場合)

Last updated at Posted at 2025-09-27

はじめに

前回の記事ではstコマンドでCesiumを起動しましたが、本記事ではViteでCesiumプロジェクトをビルドする方法について説明します。

Viteについては、公式ガイドを参照してください。以下の説明では、あらかじめNode.jsがインストールされているものとします。

プロジェクト作成

Viteでは様々なプロジェクトテンプレートを選択することができますが、本記事ではテンプレートなしでプロジェクトを作成します。

$ npm create vite@latest cesium_vite -- --template vanilla

プロジェクトを作成したら、プロジェクトディレクトリへ移動し、CesiumとViteのCesiumプラグインをインストールします。

$ npm install cesium --save-dev
$ npm install vite-plugin-cesium --save-dev

vite.config.jsの記述

テンプレートでvanillaを指定した場合はvite.config.jsを手動で作成する必要があります。vite.config.jsをプロジェクトのルートディレクトリに作成したら、以下の内容を記述します。

// vite.config.js
import { defineConfig } from 'vite'
import cesium from 'vite-plugin-cesium'

export default defineConfig({
  define: {
    // CesiumのグローバルプロパティをViteで使用するため
    CESIUM_BASE_URL: JSON.stringify('cesium')
  },
  plugins: [cesium()],
  optimizeDeps: {
    // Cesiumの依存関係を事前に最適化
    include: ['cesium']
  }
})

Webページ、スクリプトファイル

ここからはスクリプトファイル、HTMLファイルを編集していきます。プロジェクト作成時に作成されているsrc/counter.jsは必要ないので削除しておきます。

index.html

プロジェクト作成時の状態のままでも大丈夫ですが、わかりやすいようにdivコンテナのid名を変更しておきます。

<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <link rel="icon" type="image/svg+xml" href="/vite.svg" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>cesium_vite</title>
</head>

<body>
  <!-- コンテナIDを変更 -->
  <div id="cesiumContainer"></div>
  <script type="module" src="/src/main.js"></script>
</body>

</html>

src/main.js

これは前回の記事のclient.jsに記述されている内容を、Vite用に少し変更した内容を記述します。

import {
  Viewer,
  Terrain
} from "cesium";
import './style.css'

async function initializeCesium() {
  // この関数内にSandcastleのコードを貼り付ける
  const viewer = new Viewer('cesiumContainer', {
    terrain: Terrain.fromWorldTerrain(),
  });
  viewer.scene.globe.depthTestAgainstTerrain = true;
}

initializeCesium();

src/style.css

前回の記事の内容のままでほぼ大丈夫ですが、インポートのパスが異なるので注意してください。

@import url(cesium/Build/Cesium/Widgets/widgets.css);

html,
body,
#cesiumContainer {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

テスト実行、ビルド

ここまで準備できたら、以下のコマンドで実行してみます。

$ npm run dev

コマンドを実行すると以下のようにURLが表示されます。

スクリーンショット 2025-09-27 124703.png

表示されたURLにアクセスして、以下のように表示されれば成功です。

スクリーンショット 2025-09-27 125127.png

ビルドを実行するには以下のコマンドを実行します。

$ npm run build

特にビルド設定を行っていない場合は、distフォルダ内に本番環境用のファイル一式が作成されます。以下のコマンドを実行して上記と同じ用に地球が表示されれば成功です。

$ npm run preview

ビルド設定についての詳細は公式ガイドを参照してください。

9
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?