webpack与vite读取base64图片
某些特殊场景下,需要使用base64渲染图片
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxETEhUSEBAVFhIXEhIXFRYYFxcVFhYWFxYWFxcXFRcYHSggGBonIBcVITEhJSkrLi4uGB8zODMsOCgtLysBCgoKDg0OGxAQGjMlHyUrLTcuKzMrNy0tLi0tKzUtLS0vLS4rKysrLisrLTYtLTUtLS0vLS0tLS0rLSstLS0tLf/AABEIAMIBAwMBIgACEQEDEQH/xAAcAAEAAQUBAQAAAAAAAAAAAAAABwMEBQYIAgH/xABJEAABAwIDBAcEBggEAwkAAAABAAIDBBEFEiEGMUFRBxMiYXGBkRQyodFCUnKSscEVIzNTYoKy8CRDY+HC0vEIFiZEVHODk5T/xAAaAQEAAwEBAQAAAAAAAAAAAAAAAQIEAwUG/8QAMhEAAgIBAgQDBQcFAAAAAAAAAAECAxEEIQUSMUETUWFxgaGxwRQiMkKR4fAVM1Ky8f/aAAwDAQACEQMRAD8AnFERAEREAREQBERAEREAREQBERAEREAREQBERAEREAREQBERAEREAREQBERAEREAREQBERAEREAREQBERAERU552saXPcGtAuSTYDzQFRFouN7fBt20zL/xu3eIb8/RaNimPzzX62Z7u69m/dGnwQnBNk1bE335WN8XAfiVZu2ioxvq4P/sZ81Assw32VH2vuUFuU6KpK+GX9lKx/wBlwd+BVyuc6HGpYnAtcd/D8lImBdI7OpInP6xpGUkE5gfDeQfDgpIcWSQii+q6QZCf1bez3nL8G/NZLBukNhIbURlo+uDmt4i17eF0Iwb8io0tVHI0Pje1zTuLTcKshAREQBERAEREAREQBERAEREAREQBERAEREAREQBEWK2gxtlMwuJ7VtB+Z+XH1IA945jcNKzPM7ffK0auceTR+e5RRtBtPNVOu85Yweywbh3nme9WGK4lJPIZJXEuPwHADkFjnOVsFkj3JMSrdzlUy3VvUOt4oWKNQ9WjiqklyqLlVlkj4XFfWyHmmRAxQiS+pZjxV2ySyx0I71eAq5QzWE41JA7NHIWnjbcfE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pGxRRxM92ONjG/ZY0NHwCuF8C+r3D58IiIAiIgCIiAIiIAiIgCIiAwu2ddNBQ1EtNG58zYndW1oLjmOgIA1Nr5rdy5O/RtQPep578SY33vxvouy0RMHGD6WUb4ZB/I4fkpawbbCigpoY3PkzRwRtLepluXNYAQDltvG9TqvmUclOQcXzuLnOcWOGZznEZTpmJNt3es86viq6ZsdTII6uBobDK5r8s0I3QylrSQ5muV1rW7J5rrEsHIei+dU36o9AgORqaioo29ZVVfWcoKdrzI4/wAUsjAyNveMx7l6m2uka0xUbW0kJ0c2HN1rx/q1B/WP8LhvcutTTs+o30C+eyx/u2/dCZBxcZW8/wAULxzC7R9kj/ds+6PkvnscX7tn3R8kyDi7rRzV9gckRqYeteGxiaMvJvYNa4ON/G1vNdh+xRfumfdb8k9ii/dM+635JkYIYxjbqhbDIY6hj3lrg1ozakiw4KFRK3mu0fY4v3bPuj5L77JH+7Z90fJMg4vDh3+hWX2VnfFVRS2LWB1nud2WBjuyczjoN/HjZddtgYNzWjyCp1lBFK3JNEyRh3te1r2+jhZVmuaLi+5aEnCSkuxED8Qp7ZjUQ233MjN3qtV2NxVlp44o5J5X1kzmRxRukdkdlDXE2ytbv1J4Kcm7E4WDcYbSX/8AYi/5VmqemZGMsbGsbyaA0egWCvh8IxcW8pnoWcTslJSSw19SNcE2DnqXNkxQCOAEObRsdmzEag1Mg0dY/QbpoLngpNYwAAAAACwA0AHIL0i2wrjBcsVhGCyyVkuaTywiIrlAiIgCIiAIiIAiIgCIiAIiIAiIgCIiAIiIAiIgCIiAIiIAiIgCIiAIiIAiIgCIiAIiIAiIgP/Z
直接通过img标签的src属性赋值会导致占用太多行,可以将base64字符串单独放到自定义后缀的文件
下,使用时直接读取该文件
。如创建文件 img.dataurl,并存入base64字符串
webpack
需要下载对应的loader,如css需要css-loader,此时要读取文件内容,需要使用 raw-loader
npm install raw-loader --save-dev
配置webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.dataurl$/, // 匹配 .dataurl 文件
use: 'raw-loader', // 使用 raw-loader
},
// 其他规则...
],
},
};
使用
import img from "./img.dataurl"
<img src={img} alt="" />
vite
vite无需配置loader,导入时加上参数raw
即可
import img from "./img.dataurl?raw"