LoginSignup
12
5

【Vue3に向けて】viteのconfigを書いて、resolve aliasを設定する。

Last updated at Posted at 2020-09-05

はじめに

Vue3がRCになって速幾年、待ち遠しいですね。
私も今更ですが、Vue3を少しづつ試したり、viteを使ってみたりしてます。

vite、初めてHMRを見たとき、「え、本当にリロードされたの?」とびっくりしたのを覚えてます。

今回はviteでもwebpackのようにresolve aliasの設定の仕方を記事にしていきます。

やりたいこと

  • src/components/*.vueを設定したい。
    • importする時に./components/Hoge.vueとかしない。
vite-app
  ├ src
  │  ├ components
  │  ├ pages
  │  └ main.js
  └ vite.config.js

設定方法

viteには、vite.config.jsという、webpack.config.jsの様な設定ファイルを記述することでresolve aliasの設定をできます。

vite.config.jsに書ける設定は公式のこちらを見てもらうのが一番ですが、今回はresolve aliasの部分だけ抜粋して紹介。
公式のファイルを読んでるとこんな文章が、

vite/config.js
  /**
   * Import alias. The entries can either be exact request -> request mappings
   * (exact, no wildcard syntax), or request path -> fs directory mappings.
   * When using directory mappings, the key **must start and end with a slash**.
   *
   * Example `vite.config.js`:
   * ``` js
   * module.exports = {
   *   alias: {
   *     // alias package names
   *     'react': '@pika/react',
   *     'react-dom': '@pika/react-dom'
   *
   *     // alias a path to a fs directory
   *     // the key must start and end with a slash
   *     '/@foo/': path.resolve(__dirname, 'some-special-dir')
   *   }
   * }
   * ```
   */

// alias a path to a fs directoryの部分の通りに設定してしまえば良いのだが注意点

// the key must start and end with a slash

どうやら、/に始まる様に設定しなくてはならないらしい(パッケージに大してalias貼るのとバチらない様にだろうか)

ともかく設定する。

  • プロジェクトのrootディレクトリにvite.config.jsを作成する。
vite.config.js
import path from 'path'

module.exports = {
  alias: {
    // alias a path to a fs directory
    // the key must start and end with a slash
    '/@components/': path.join(__dirname, 'src/components')
  }
}

設定はこれで終わり。
vueファイルで下記の様にimportを書いてあげることでcomponentを呼び出すことができる。

pages/index.vue
<script>
import Hoge from '/@component/Hoge.vue'

export default {
  components: {
    AppTimeTable
  }
}
<script>

終わりに

vite.config.js、設定を見てみるといろいろできそうなのでもう少しみてみて、まとめようと思います。
それにしてもfsのaliasは/から始めなくちゃいけないのが少し変な感じがしてしまいますね。。。
vscodeでパスかく時、localの/配下を保管してしまうw
jsconfig.jsonもしっかり書いてあげねばだ。

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