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

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

问题描述

近日尝试使用vite+vue3+vant开发项目过程中,参考vant官网开发指南->快速上手->引入组件
在这里插入图片描述

按照上述配置好后,运行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官网的代码如下:
在这里插入图片描述
在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,问题解决。

猜你喜欢

转载自blog.csdn.net/weixin_42099193/article/details/123376127