Vite: resolve.alias - 如何解析路径?

新手上路,请多包涵

resolve.alias 能做什么?它不会解析以下路径:

 // vite.config.js
import { defineConfig } from 'vite'
import path from 'path'

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

在我的 HTML 中:

 <img src="@/assets/images/sample-1.jpg">

浏览器控制台报错:

 GET http://localhost:3000/@/assets/images/sample-1.jpg
Failed to load resource: the server responded with a status of 404 (Not Found)
client:180 [vite] connecting...
client:202 [vite] connected.

任何想法如何正确地做到这一点?

原文由 Run 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 929
2 个回答

npm install @rollup/plugin-alias –save-dev

或者

yarn add -D @rollup/插件别名

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

const projectRootDir = resolve(__dirname);

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    alias({
      entries: [
        {
          find: '@',
          replacement: resolve(projectRootDir, 'src')
        }
      ]
    })
  ],
  server: {
    host: '0.0.0.0',
    port: 10086,
    open: false,
    cors: true,
  },
  build: {
    outDir: 'dist',
  }
})

或者


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

const projectRootDir = resolve(__dirname);

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    alias(),
    vue()
  ],
  resolve: {
    alias: {
      "@": resolve(projectRootDir, "src"),
    },
  },
  server: {
    host: '0.0.0.0',
    port: 10086,
    open: false,
    cors: true,
  },
  build: {
    outDir: 'dist',
  }
})

原文由 keyboard_wang 发布,翻译遵循 CC BY-SA 4.0 许可协议

版本 2.7.12(我当前版本)的一个简单解决方案是将别名声明为 数组

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

export default defineConfig({
  plugins: [ vue() ],
  resolve: {
    alias: [
      { find: '@', replacement: path.resolve(__dirname, './src') },
      { find: '@config', replacement: path.resolve(__dirname, './src/config') },
      { find: '@plugins', replacement: path.resolve(__dirname, './src/plugins') },
      { find: '@views', replacement: path.resolve(__dirname, './src/views') },
      { find: '@mixins', replacement: path.resolve(__dirname, './src/mixins') },
      { find: '@svg', replacement: path.resolve(__dirname, './src/svg') },
      { find: '@models', replacement: path.resolve(__dirname, './src/models') },
      { find: '@components', replacement: path.resolve(__dirname, './src/components') },
    ]
  }
})

检查类型时可以看到合法的格式:

 resolve?: ResolveOptions & {
  alias?: AliasOptions;
};

其中 AliasOptions 是一个别名 数组

 export declare type AliasOptions = readonly Alias[] | { [find: string]: string }

原文由 widow.dad 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏