概要
Next.jsで別のコンポーネントをimportするとき、デフォルトでは相対パスで ../components/Nav
のように指定することでimportできます。
importしているコンポーネントが多いとき、コンポーネントの配置場所が変わったときに変更するのが手間なのでwebpack.resolve.aliasを設定しておくことで、webpackが絶対パスでモジュール間の依存を解決してくれます。
設定方法
next.config.js
const withTypescript = require("@zeit/next-typescript");
const withSass = require("@zeit/next-sass");
const path = require('path'); // 追記
module.exports = withTypescript(
withSass({
webpack(config) {
config.resolve.alias['~'] = path.join(__dirname) // 追記
return config;
}
})
);
TypeScriptの場合、tsconfigにも追記する必要があります。
tsconfig.json
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"~/*": ["./*"]
},
...
上記のように設定することで、以下のようにimportできるようになります。
pages/index.tsx
import React from 'react'
import Nav from '~/components/Nav'
const Home = () => {
return (
<>
<Nav />
</>
)
}
export default Home