`Vue3 - Vite` プロジェクトエイリアス src から @ が機能しない 質問する

`Vue3 - Vite` プロジェクトエイリアス src から @ が機能しない 質問する

vue3 - vite私は次のようなコンポーネントをインポートしてプロジェクトをインストールしました

import Component from '../../../../components/Component.vue'

私はsrcフォルダにエイリアスを付けて、

import Component from '@/components/Component.vue'

これは私のvite.config.jsです

import vue from '@vitejs/plugin-vue'

/**
 * https://vitejs.dev/config/
 * @type {import('vite').UserConfig}
 */
export default {
    plugins: [
        vue({
            template: {
                compilerOptions: {
                    // ...
                }
            }
        })
    ]
}

何か見落としているのでしょうか? 他に何をすればいいのでしょうか?

ベストアンサー1

2023年アップデート

最終的に私にとってうまくいったのは次の通りです:

ヴィテコンフィグ:

import { fileURLToPath, URL } from "url";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: [
      { find: '@', replacement: fileURLToPath(new URL('./src', import.meta.url)) },
      { find: '@assets', replacement: fileURLToPath(new URL('./src/shared/assets', import.meta.url)) },
      { find: '@cmp', replacement: fileURLToPath(new URL('./src/shared/cmp', import.meta.url)) },
      { find: '@stores', replacement: fileURLToPath(new URL('./src/shared/stores', import.meta.url)) },
      { find: '@use', replacement: fileURLToPath(new URL('./src/shared/use', import.meta.url)) },
    ],
  },
});

TS構成:

{
  ...
  "compilerOptions": {
    ...
    "paths": {
      "@/*": ["./src/*"],
      "@assets/*": ["./src/shared/assets/*"],
      "@cmp/*": ["./src/shared/cmp/*"],
      "@stores/*": ["./src/shared/stores/*"],
      "@use/*": ["./src/shared/use/*"]
    }
  }
}

2022年アップデート

このソリューションは、新しいプロジェクトを作成するときにデフォルトで提供されます。npm init vue@latest

import { fileURLToPath, URL } from "url";

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
});

コンポーネントでは以下を使用します@/:

<script setup>
import HelloWorld from "@/components/HelloWorld.vue";
</script>


私にとってはこれが効果的でした:

import path from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@/': `${path.resolve(__dirname, 'src')}/`
    }
  }
})

次にコンポーネントで:

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <HelloWorld msg="Hello Vue 3 + Vite" />
</template>

<script>
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

おすすめ記事