简体   繁体   English

`Vue3 - Vite`项目别名src到@不工作

[英]`Vue3 - Vite` project alias src to @ not working

I have installed the project with vue3 - vite importing a component like我已经用vue3 - vite导入了一个像

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

i just want to alias the src folder and do我只想给 src 文件夹起别名并做

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

this is my vite.config.js这是我的 vite.config.js

import vue from '@vitejs/plugin-vue'

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

am i missing something?我错过了什么吗? what else should i do?我还应该做什么?

In the vite.config.js file write the below code blocksvite.config.js文件中写入以下代码块

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

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  }
})

Update 2022 2022 年更新

This solution comes by default from when creating a new project with npm init vue@latest此解决方案默认来自使用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)),
    },
  },
});

In components use @/ :在组件中使用@/

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


This is what worked for me:这对我有用:

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')}/`
    }
  }
})

Then in components:然后在组件中:

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

Vue 3 Vite TypeScript Vue 3 Vite TypeScript

vite.config.ts vite.config.ts

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

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  }
})

To remove warnings and add hint to downloads with @/使用@/删除警告并添加下载提示

tsconfig.json tsconfig.json

{
  "compilerOptions": {
    ...
    "paths": {
      "@/*": ["./src/*", "./dist/*"]
    }
  }
}

Vote up people below too except answer of question creator please.除了问题创建者的回答,请给下面的人投票。 He copy paste answer form person who helped him in same day he asked question.他在他提问的同一天复制粘贴答案表格帮助他的人。

Unlike webpack , Vite doesn't have @ aliased to src by default.webpack不同, Vite默认没有@别名为src There is discussion of this at the following issue: https://github.com/vitejs/vite/issues/279以下问题对此进行了讨论: https://github.com/vitejs/vite/issues/279

Ultimately you need to create an alias:最终你需要创建一个别名:

// vite.config.js 
module.exports = {
  alias: {
    '/@': path.resolve(__dirname, './src')
  }
}

// Your config 
export default {
  alias: {
    '/@': path.resolve(__dirname, './src')
  },
  plugins: [ ... ]
 }

Then you need to use /@ in your files, eg:然后你需要在你的文件中使用/@ ,例如:

import foo from '/@foo'

Here's what worked for me...这对我有用...

import vue from '@vitejs/plugin-vue'
const path = require('path')

export default {
  alias: {
    '/@': path.resolve(__dirname, './src')
  },
  plugins: [vue()]
}

I tried most of the above solutions and unfortunately did not work.我尝试了上述大多数解决方案,但不幸的是没有奏效。 The following did.以下做到了。

In my jsconfig.json在我的 jsconfig.json

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

and in my vite.config.js在我的 vite.config.js

import { fileURLToPath } from "url";
import path from "path";

import { defineConfig } from "vite";

export default defineConfig({
  resolve: {
    alias: {
      "@": path.resolve(path.dirname(fileURLToPath(import.meta.url)), "src"),
    },
  },
});

In my Vite 2.7.x在我的 Vite 2.7.x

import vue from '@vitejs/plugin-vue'
import path from 'path'
 
...    
...
 resolve: {
   alias: [
      { find: '@', replacement: path.resolve(__dirname, './src') },
      { find: '...', replacement: path.resolve(__dirname, '...') },
      { find: '...', replacement: path.resolve(__dirname, '...') },
      { find: '...', replacement: path.resolve(__dirname, '...') },
   ]
}

Export path resolve function导出路径解析 function

Problrem问题

@/ alias doesn't work in :src dynamic attribure, so that you can't resolve asset file path dynamically. @/别名在:src动态属性中不起作用,因此您无法动态解析资产文件路径。

Solution解决方案

  1. In the common ts code, define path resolve function(ie img() ) using import.meta.url .在常见的 ts 代码中,使用import.meta.url定义路径解析函数(即img() )。
  2. Use img() in the vue script.在 vue 脚本中使用img()

Files文件

/src
  /assets/img/
    logo.png
  Util.ts
  App.vue

Util.ts实用程序

export const srcRoot = import.meta.url;
export function img(name:string){
  return new URL(`./assets/img/${name}.png`, srcRoot)
}

App.vue应用程序.vue

<script>
import {img} from "./Util";
</script>

<template>
<img  :src="img('logo')" />
</template>

In my blog post i describe how to configure this with Vite, TypeScript and Jest: https://divotion.com/blog/how-to-configure-import-aliases-in-vite-typescript-and-jest .在我的博客文章中,我描述了如何使用 Vite、TypeScript 和 Jest 进行配置: https://divotion.com/blog/how-to-configure-import-aliases-in-vite-typescript-and-jest For Vite change the vite.config.ts file to:对于 Vite,将vite.config.ts文件更改为:

// vite.config.ts
import { defineConfig } from "vite";
import path from "path";

export default defineConfig({
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
});

This seems to work for me and is shorter:这似乎对我有用,而且更短:

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

export default defineConfig({
    resolve: {
        alias: {
            '@': path.resolve('./resources'),
        }
    },
    plugins: [
        laravel({
            input: 'resources/js/app.js',
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM