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?

More than 1 year has passed since last update.

【React】エイリアスの設定よる簡潔なインポート

Posted at

エイリアスとは?

エイリアスは、長いファイルパスを短くするために使用されるショートカットのようなもので、ファイルの絶対パスを簡単に参照するための方法。@が用いられる。

設定手順

  • react-app-rewiredパッケージをインストール
npm install react-app-rewired react-app-rewire-alias --save-dev
  • config-overrides.tsに以下のコードを追加
config-overrides.ts
const { alias } = require('react-app-rewire-alias');

module.exports = function override(config) {
  alias({
    '@': './src',
  })(config);

  return config;
};
  • tsconfig-pathsパッケージをインストール
npm install tsconfig-paths --save-dev
  • tsconfig.jsonに以下の設定を追加
tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  },
}
  • tsconfig-pathsを使ってTypeScriptでconfig-overrides.tsを実行できるように、package.jsonのscriptsを次のように変更。
package.json
"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  "test": "react-app-rewired test",
  "eject": "react-scripts eject",
  "start:ts": "ts-node -r tsconfig-paths/register config-overrides.ts",
  "build:ts": "ts-node -r tsconfig-paths/register config-overrides.ts"
},
  • 以下のコマンドでTypeScript版の設定が適用
npm install ts-node --save-dev

npm run start:ts

これで@で./srcまでを省略して表すことができるようになる。

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?