简体   繁体   English

包括来自其他文件的base64图像?

[英]Including base64 images from other files?

目前我正在通过data:在我的css和img标签中使用base64图像data:你可以想象通过在文件中包含整个base64代码可能会变得非常混乱,因此我想知道是否有一种方法可以从中导入它外部文件以及如何使用webpack处理这些文件?

You could try using gulp-css-base64 plugin that will read all images from folders where your images are located. 您可以尝试使用gulp-css-base64插件来读取图像所在文件夹中的所有图像。 Each time you run gulp task it will update css file with new images (or update current ones). 每次运行gulp任务时,它都会使用新映像更新css文件(或更新当前的映像)。

gulp.task('default', function () {
    return gulp.src('src/css/input.css')
        .pipe(cssBase64({
            baseDir: "../../images",
            maxWeightResource: 100,
            extensionsAllowed: ['.gif', '.jpg']
        }))
        .pipe(gulp.dest('dist'));
});

webpack's url-loader is made exactly for this purpose! webpack的url-loader就是为了这个目的而制作的!

To configure it, just add this to the loaders of your webpack-config: 要配置它,只需将其添加到webpack-config的加载器:

{
  test: /\.(svg|jpg|png|gif)$/,
  loader: 'url?limit=10000',
}

URL-loader returns a data URI for the file you require/import if it's size is below the specified limit, otherwise it bundles the file and returns the URL. 如果URL大小低于指定的限制,则URL-loader返回您需要/导入的文件的数据URI,否则它会捆绑文件并返回URL。

The limit is specified in bytes, so 10000 will roughly mean any file under 10kB will be returned as a data URI. 限制以字节为单位指定,因此10000大致意味着任何10kB以下的文件都将作为数据URI返回。 If you specify no limit, everything will be encoded as data URI. 如果您指定无限制,则所有内容都将编码为数据URI。 I suggest you only use it for small files, however. 不过,我建议你只将它用于小文件。

So, once it's set up, var smallImageUri = require('./smallImage.png'); 因此,一旦设置var smallImageUri = require('./smallImage.png');var smallImageUri = require('./smallImage.png'); should give you exactly what you need! 应该给你你所需要的! A data URI if smallImage.png is below your configured limit, or the URL to the bundled image when it's larger. 如果smallImage.png低于配置的限制, smallImage.png数据URI;如果为smallImage.png则为捆绑图像的URL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM