0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactでパスエイリアスを設定する

Posted at

初めに

Reactでサイトを作っていく中で、ファイルの階層が深くなってきた。
そこでcracoを用いてパスエイリアスを設定したのでまとめておく。

インストール

npm install -D @craco/craco

設定方法

  1. ルートディレクトリにcraco.config.jsを作成
  2. craco.config.jsを編集
    const path = require('path');
    
    module.exports = {
            webpack: {
                    alias: {
                            '@': path.resolve(__dirname, 'src/'),
                            '@parts': path.resolve(__dirname, 'src/ui-parts/'),
                            '@pages': path.resolve(__dirname, 'src/pages/'),
                            '@layouts': path.resolve(__dirname, 'src/layouts/'),
                    },
            },
    };
    
  3. package.jsonを変更
    以下を追加
    "scripts": {
      "start": "craco start",
      "build": "craco build",
      "test": "craco test"
    }
    

エディタで補完を効かせる

VSCodeなどで保管を効かせる。
jsconfig.jsonまたはtsconfig.jsonに追記。

{
    "compilerOptions": {
        "baseUrl": "src",
        "paths": {
            "@parts/*": [
                "ui-parts/*"
            ],
            "@pages/*": [
                "pages/*"
            ],
            "@layouts/*": [
                "layouts/*"
            ]
        }
    }
}

終わりに

比較

import Head from '../../../layouts/Head/Head';
import Head from '@layouts/Head/Head';

だいぶ楽になった。

~Thank you for readin~

0
1
3

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?