vue3引入图片 无法使用require, vue3+vite构建项目使用require引入包出现问题需要用newURL来动态引入图片等静态资源

在vue3中 require引入图片的本地资源报错Uncaught (in promise) ReferenceError: require is not defined

<template>

<img :src="imageSrc" alt="My Image"> </template>

<script>

   import imageSrc from '@/assets/image.png'; export default { data() { return { imageSrc }; } };

</script>

 使用vue3+vite构建的项目使用require会报错

解决方案

一、

使用 @rollup/plugin-commonjs 插件,用于将CommonJS模块转换为ES6模块的Rollup插件.
1、安装@rollup/plugin-commonis 插件
终端中输入

npm i @rollup/plugin-commonjs
 

2、在vite.config.ts配置中添加该插件,注意 commonjs0必须在vue()上面,否则不生效 

import commonjs from '@rollup/plugin-commonjs';

const plugins = [
    commonjs() as any,// 要放在第一行,否则不生效
];
 

3、随意导入commonjs工具包

import SoftAlgorithm from '../SDK/soft-algorithm-min.js';
console.log('引入成功:', SoftAlgorithm);
 

当consle能打印出来则,引入成功 

二、

使用new URL(‘路径’,import.meta.url).href

 用法:

new URL(‘路径’,import.meta.url).href

 pcImage: new URL("@/assets/qy-pc.JPG", import.meta.url).href,

 在构建之后相对路径会打包不到具体文件,使用@/解决

"@/assets/qy-pc.JPG"  

最近更新

  1. TCP协议是安全的吗?

    2024-04-24 08:30:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-24 08:30:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-24 08:30:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-24 08:30:03       20 阅读

热门阅读

  1. k8s的资源对象Deployment该如何使用?

    2024-04-24 08:30:03       14 阅读
  2. python读取pdf表格并合并为excel

    2024-04-24 08:30:03       16 阅读
  3. ILM ADO storage tiering policy on table partition

    2024-04-24 08:30:03       11 阅读
  4. Linux系统上C++使用alsa库播放声音文件

    2024-04-24 08:30:03       14 阅读
  5. 深度学习基础之《TensorFlow框架(14)—TFRecords》

    2024-04-24 08:30:03       14 阅读
  6. LeetCode //C - 29. Divide Two Integers

    2024-04-24 08:30:03       12 阅读
  7. 关于上传自己本地项目到GitHub的相关命令

    2024-04-24 08:30:03       12 阅读
  8. Unity UI擦除效果

    2024-04-24 08:30:03       13 阅读
  9. Rust:遍历 BinaryHeap

    2024-04-24 08:30:03       12 阅读
  10. 使用Python实现语音识别与处理模型

    2024-04-24 08:30:03       12 阅读