在vue3+vite项目下按需引入vant报错Failed to resolve import解决方案

    • 问题描述
    • 原因分析
    • 解决方案

问题描述

近日尝试使用vite+vue3+vant开发项目过程中,参考vant官网开发指南->快速上手->引入组件
在vue3+vite项目下按需引入vant报错Failed to resolve import解决方案

按照上述配置好后,运行vite环境报错:Failed to resolve import

原因分析

根据报错信息,发现是vant的样式引入路径不对。
程序解析为:项目路径/node_modules/vant/lib/vant/es/组件/style
实际应该是:项目路径/node_modules/vant/lib/ vant/es/组件/style
多了一个vant/lib路径。

解决方案

vite.config.js文件中解析至正确路径。
vant官网的代码如下:
在vue3+vite项目下按需引入vant报错Failed to resolve import解决方案
在styleImport内添加代码块:

libs: [
        {
          libraryName: 'vant',
          esModule: true,
          resolveStyle: name => `../es/${name}/style`
        }
      ]

完整代码如下:

import vue from '@vitejs/plugin-vue';
import styleImport, { VantResolve } from 'vite-plugin-style-import';
export default {
  plugins: [
    vue(),
    styleImport({
      resolves: [VantResolve()],
      libs: [
        {
          libraryName: 'vant',
          esModule: true,
          resolveStyle: name => `../es/${name}/style`
        }
      ]
    }),
  ],
};

修改后,重新运行vite,问题解决。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。