vite 中定义了 alias 但是在工程中使用 提示文件解析失败

Created on 14 Dec 2020  ·  4Comments  ·  Source: vitejs/vite

  • required vite version: "^1.0.0-rc.13",
  • required Operating System: mac os
  • required Node version: v10.16.0

vite vite.config.js 中配置

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

运行项目报错解析模块错误[vite] Failed to resolve module import "@/components/customTable/index.vue". (imported by /src/main.js)

pending triage

Most helpful comment

import { UserConfig } from 'vite'

const aliasConfig: Record<string, string> = {
  '@/': 'src/',
  '@img/': 'src/assets/img/',
}

export default {
  port: 2009,
  resolvers: [
    {
      alias(id) {
        let path = ''
        Object.keys(aliasConfig).find((key) => {
          if (id.startsWith(key)) {
            const dir = '/' + aliasConfig[key]
            path = dir + id.slice(key.length)
          }
          return !!path
        })
        console.log(path)

        return path
      },
    },
  ],
} as UserConfig

All 4 comments

You can try it
/@/components/customTable/index.vue

As @MangoTsing said.

import { UserConfig } from 'vite'

const aliasConfig: Record<string, string> = {
  '@/': 'src/',
  '@img/': 'src/assets/img/',
}

export default {
  port: 2009,
  resolvers: [
    {
      alias(id) {
        let path = ''
        Object.keys(aliasConfig).find((key) => {
          if (id.startsWith(key)) {
            const dir = '/' + aliasConfig[key]
            path = dir + id.slice(key.length)
          }
          return !!path
        })
        console.log(path)

        return path
      },
    },
  ],
} as UserConfig
import { UserConfig } from 'vite'

const aliasConfig: Record<string, string> = {
  '@/': 'src/',
  '@img/': 'src/assets/img/',
}

export default {
  port: 2009,
  resolvers: [
    {
      alias(id) {
        let path = ''
        Object.keys(aliasConfig).find((key) => {
          if (id.startsWith(key)) {
            const dir = '/' + aliasConfig[key]
            path = dir + id.slice(key.length)
          }
          return !!path
        })
        console.log(path)

        return path
      },
    },
  ],
} as UserConfig

为什么官方没这样处理呢?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

haikyuu picture haikyuu  ·  3Comments

shen-zhao picture shen-zhao  ·  3Comments

ais-one picture ais-one  ·  3Comments

ashubham picture ashubham  ·  3Comments

Dykam picture Dykam  ·  4Comments