LoginSignup
2
1

Vite によるビルド最適化:Minification、Tree Shaking、Code Splitting、アセットの最適化

Last updated at Posted at 2024-05-01

Vite は現代のウェブアプリケーション開発において、ビルド速度の高速化と最終的なファイルサイズの削減を実現する強力なツールです。特にproductionビルドでは、以下の最適化技術がパフォーマンス向上に貢献します。
vite build --mode productionで行われるビルドについて、環境変数の読み込みの違いもありますが、もう少し深堀りして、Minification、Tree Shaking、Code Splitting、アセットの最適化の 4 つの仕組みについて解説します。

Minification(圧縮)

概念

Minification は、不要な文字(空白、コメント、改行など)を削除し、変数名を短縮することでコードのファイルサイズを小さくする技術です。

ソースコードの例

// example.js
import { add } from "./math.js";

console.log(add(5, 3));
// math.js
export function add(a, b) {
  return a + b;
}

ビルド後の違い

productionビルド後のコードは次のように圧縮されます。

// example.js(圧縮後)
console.log(8);

Tree Shaking

概念

Tree Shaking は、使用されていないコード(Dead code)を取り除くプロセスです。これにより、最終的なバンドルサイズが削減されます。

ソースコードの例

// utils.js
export const add = (a, b) => a + b;
export const unusedFunction = () => console.log("This is unused");
// main.js
import { add } from "./utils.js";

console.log(add(1, 2));

ビルド後の違い

productionビルドでは、unusedFunctionはバンドルから削除されます。

// main.js(ビルド後)
console.log(3);

Code Splitting(コード分割)

概念

Code Splitting は、アプリケーションを複数のチャンクに分割し、必要なときにのみチャンクをロードする技術です。

ソースコードの例

// main.js
const button = document.createElement("button");
button.innerText = "Load";
button.onclick = async () => {
  const { moduleFunction } = await import("./module.js");
  moduleFunction();
};
document.body.appendChild(button);
// module.js
export const moduleFunction = () => console.log("Module loaded");

ビルド後の違い

productionビルドでは、module.jsは別のファイルとして分割され、main.jsから動的にロードされます。

アセットの最適化

概念

アセットの最適化は、画像やフォントなどのリソースファイルのサイズを削減し、ロード時間を短縮する技術です。

ソースコードの例

<!-- index.html -->
<img src="./large-image.png" alt="A large image" />

ビルド後の違い

productionビルドでは、large-image.pngは圧縮され、ファイルサイズが小さくなります。また、適切な場合は WebP などのより効率的なフォーマットに変換されることもあります。
画像ファイル(例えば、PNG、JPG、SVG など)の圧縮は、Vite のデフォルト設定では直接行われません。
画像最適化に特化した Vite プラグインをプロジェクトに追加することで、ビルドプロセス中に自動的に画像を圧縮できます。例えば、vite-plugin-imagemin は人気のあるプラグインの一つで、複数の画像フォーマットに対応した圧縮オプションがあります。


これらの最適化技術を通じて、Vite はproductionビルドのパフォーマンスを大幅に向上させています。Web アプリケーションや Web ページのロード時間を短縮することで、ユーザーの離脱率の軽減やユーザーエクスペリエンスを改善することが見込めますので、よしなにやってくれている Vite は便利です。

2
1
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
2
1