0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

vite-tsconfig-pathsを使ったエイリアス設定方法

Posted at

vite-tsconfig-pathsを使用すると、ViteプロジェクトでTypeScriptのパスエイリアスを簡単に設定できます。以下に、その手順と具体的なインポート例を説明します。

1. vite-tsconfig-pathsを使ったエイリアス設定方法

ステップ1: パッケージのインストール

まず、開発環境にvite-tsconfig-pathsをインストールします。

npm install -D vite-tsconfig-paths

ステップ2: tsconfig.jsonの設定

次に、プロジェクトのルートディレクトリにあるtsconfig.jsonファイルに、エイリアスの設定を追加します。

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

この設定により、@/src/ディレクトリに対応させることができます。

ステップ3: vite.config.tsの設定

最後に、vite.config.tsファイルでvite-tsconfig-pathsプラグインを読み込み、Viteのプラグインとして登録します。

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
  plugins: [
    react(),
    tsconfigPaths()
  ]
});

これにより、tsconfig.jsonで設定したパスエイリアスがViteのビルドプロセスでも適用されます。

2. src/App.tsxでのインポート例

上記の設定を行った後、src/App.tsxでのインポートは以下のように記述できます。

import React from 'react';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import { fetchData } from '@/utils/api';

const App: React.FC = () => {
  // コンポーネントのロジック
  return (
    <div>
      <Header />
      {/* 他のコンポーネントや要素 */}
      <Footer />
    </div>
  );
};

export default App;

ここで、@/はプロジェクトのsrc/ディレクトリを指しています。したがって、@/components/Headersrc/components/Headerを、@/utils/apisrc/utils/apiをそれぞれ参照します。このようにエイリアスを使用することで、深い階層の相対パスを避け、コードの可読性と保守性を向上させることができます。

以上の手順で、vite-tsconfig-pathsを使用したエイリアス設定と、その具体的なインポート方法を実現できます。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?