LoginSignup
9
3

More than 3 years have passed since last update.

Next.js にaliasを追加してimportの手間を減らす

Last updated at Posted at 2020-01-09

Next.jsのデフォルト設定では相対importを使うようになっていて、大量のコンポーネントをimportする際に何度も ../../ を書く必要があり面倒です。

この問題は next.config.js 内の webpack config をカスタマイズすることで解決できます。

aliasのカスタマイズ

const path = require('path');

module.exports = {
  webpack: config => {
    config.resolve.alias['~'] = path.resolve(__dirname);
    return config;
  }
};

これにより、 import {Button} from "~/components" のように使うことができます。

VSCodeの設定

VSCodeをしているのであれば、下記を tsconfig.json に追加することで補完が効くようになります。


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

参考

https://remysharp.com/2019/11/04/nice-imports-with-nextjs#targetText=That's%20it.%20Now%20I%20can%20import%20from%20'~%2Fcomponents%2FWidget'%20and%20all%20is%20well.

9
3
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
3