LoginSignup
8
7

More than 3 years have passed since last update.

next.jsで絶対パスを使用する方法(TypeScript)

Last updated at Posted at 2020-04-24

babel-plugin-module-resolverをインストール

$ npm install --save-dev babel-plugin-module-resolver

or

$ yarn add --dev babel-plugin-module-resolver

.babelrcにカスタムルート、エイリアスを設定(.babelrcがなければ作成する)

.babelrc
{
    "presets": [
        "next/babel"
    ],
    "plugins": [
        [
            "module-resolver",
            {
                "root": [
                    "."
                ],
                "alias": {
                    "@": "./src"
                }
            }
        ]
    ]
}

tsconfig.jsonにbaseUrlとパスを設定

tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
  }
}

これでimport Button from '@/components/button'のように使用できる

package.json

package.json
"dependencies": {
    "next": "latest", (9.3)
    "react": "^16.9.0",
    "react-dom": "^16.9.0",
    "react-redux": "^7.1.0",
    "redux": "^3.6.0",
    "redux-devtools-extension": "^2.13.2"
  },
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^13.13.1",
    "@types/react": "^16.9.34",
    "babel-plugin-module-resolver": "^4.0.0",
    "typescript": "^3.8.3"
  }
8
7
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
8
7