简体   繁体   中英

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. Each time you run gulp task it will update css file with new images (or update current ones).

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!

To configure it, just add this to the loaders of your 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.

The limit is specified in bytes, so 10000 will roughly mean any file under 10kB will be returned as a data URI. If you specify no limit, everything will be encoded as data URI. I suggest you only use it for small files, however.

So, once it's set up, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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