10
5

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.

Keisuke Death MarchAdvent Calendar 2023

Day 9

【Next.js】VSCode上で絶対パスのimport補完ができるようにしたい

Last updated at Posted at 2023-12-08

はじめに

VSCode上で絶対パスでimport補完できるように手順をまとめました。

Image from Gyazo

環境構築

Next.js14で進めます。オプションは全てデフォルトです。

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@エイリアスとして使えるようになります。

スクリーンショット 2023-12-08 9.35.39.png

また、typescript.preferences.importModuleSpecifiernon-relativeに変更することで、コンポーネント呼び出しのimport補完時にでも絶対パスでimportされるようになります。

スクリーンショット 2023-12-08 9.19.43.png

10
5
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
10
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?