はじめに
VSCode上で絶対パスでimport補完できるように手順をまとめました。
環境構築
Next.js
は14で進めます。オプションは全てデフォルトです。
npx create-next-app@latest
Need to install the following packages:
create-next-app@14.0.4
Ok to proceed? (y)
✔ What is your project named? … my-app
✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like to use `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to customize the default import alias (@/*)? … No / Yes
Creating a new Next.js app in /Users/keisukesakuma/projects/absolute-path-app.
Using npm.
Initializing project with template: app-tw
Installing dependencies:
- react
- react-dom
- next
Installing devDependencies:
- typescript
- @types/node
- @types/react
- @types/react-dom
- autoprefixer
- postcss
- tailwindcss
- eslint
- eslint-config-next
added 333 packages, and audited 334 packages in 51s
117 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
Initialized a git repository.
tsconfig.json
に設定を追記します。
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"baseUrl": ".",
"plugins": [
{
"name": "next",
"@/*": ["./src/app/*"] //追加
}
],
"paths": {
"@/*": ["./src/app/*"] //追加
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
./src/app
が@
エイリアスとして使えるようになります。
また、typescript.preferences.importModuleSpecifier
をnon-relative
に変更することで、コンポーネント呼び出しのimport
補完時にでも絶対パスでimport
されるようになります。