Giter Site home page Giter Site logo

gulp-css-base64's Introduction

gulp-css-base64

Build Status Coverage Status Dependencies NPM Version Download Month

This gulp task converts all data found within a stylesheet (those within a url( ... ) declaration) into base64-encoded data URI strings. This includes images and fonts.

Inspired by grunt-image-embed and written following gulp's guidelines.

Features

  • Supports local and remote resources.
  • Supports buffer (and stream WIP).
  • [>] Ability to define a relative base directory to gulpfile.js. Default is the current directory.
  • [>] Ability to specify a weight limit. Default is 32kB which is IE8's limit.
  • [>] Ability to filter on file extensions. Default there is no filter.
  • [>] Ignore a resource by specifying a directive comment in CSS.
  • Existing data URIs will be ignored.
  • Existing SVG masks will be ignored.

Install

Install this plugin with the command:

npm install --save-dev gulp-css-base64

Usage

var cssBase64 = require('gulp-css-base64');

//Without options
gulp.task('default', function () {
    return gulp.src('src/css/input.css')
        .pipe(cssBase64())
        .pipe(gulp.dest('dist'));
});

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

Options

options.baseDir

Type: String

Default value: ``

Note: If you have absolute image paths in your stylesheet, the path specified in this option will be used as the base directory. By default plugin used the current directory of gulpfile.js to find local resources.

options.maxWeightResource

Type: Number

Default value: 32768

options.extensionsAllowed

Type: Array

Default value: []

Ignore a specific resource

You can ignore a resource with a comment /*base64:skip*/ in CSS file after url definition.

.ignored{
  background: url(image.png); /*base64:skip*/
}
.encoded{
  background: url(image.jpg);
}

License

Copyright (c) 2014 Mehdy Dara under the MIT License.

gulp-css-base64's People

Contributors

gedkott avatar idontsov avatar zckrs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

gulp-css-base64's Issues

Problem with encoding fonts

Hello.

I have fonts with url in style.css:

../fonts/font-name.eot?mjlrlo#iefix

This plugin ignore this fonts because path.extname(result[1]) !== '.ttf' from my extensionsAllowed option (extensionsAllowed: ['.eot', '.svg', '.ttf', '.woff']).

Please, fix it.

Ignore encoding when it's an ID pointing to a SVG mask

It's possible to leave an ID behind an URL in the CSS like that:

mask-image: url("#stark-svg-mask");

It's allowed but this gulp task complains such cases with:

[22:23:08] gulp-css-base64 : File not found /home/michael.heuberger/binarykitchen/code/frontend_assessment/public/css/public/#stark-svg-mask

Any chance you could fix this asap? If you need an example, use http://codepen.io/iamvdo/pen/maJhu

Thx!

Wrong MIME type for CSS imports

gulp-css-base64 currently converts the following CSS import

@import url('https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic&subset=latin');

into this:

@import url('data:application/octet-stream;base64,QGZvbnQtZmFjZSB7CiAgZm9udC1mYW1pbHk6ICdMYXRvJzsKICBmb250LXN0eWxlOiBub3JtYWw7CiAgZm9udC13ZWlnaHQ6IDQwMDsKICBzcmM6IGxvY2FsKCdMYXRvIFJlZ3VsYXInKSwgbG9jYWwoJ0xhdG8tUmVndWxhcicpLCB1cmwoaHR0cHM6Ly9mb250cy5nc3RhdGljLmNvbS9zL2xhdG8vdjExL3YwU2RjR0ZBbDJhZXpNOVZxX2FGVFEudHRmKSBmb3JtYXQoJ3RydWV0eXBlJyk7Cn0KQGZvbnQtZmFjZSB7CiAgZm9udC1mYW1pbHk6ICdMYXRvJzsKICBmb250LXN0eWxlOiBub3JtYWw7CiAgZm9udC13ZWlnaHQ6IDcwMDsKICBzcmM6IGxvY2FsKCdMYXRvIEJvbGQnKSwgbG9jYWwoJ0xhdG8tQm9sZCcpLCB1cmwoaHR0cHM6Ly9mb250cy5nc3RhdGljLmNvbS9zL2xhdG8vdjExL0R2bEZCU2NZMXItRk10WlNZSVlvWXcudHRmKSBmb3JtYXQoJ3RydWV0eXBlJyk7Cn0KQGZvbnQtZmFjZSB7CiAgZm9udC1mYW1pbHk6ICdMYXRvJzsKICBmb250LXN0eWxlOiBpdGFsaWM7CiAgZm9udC13ZWlnaHQ6IDQwMDsKICBzcmM6IGxvY2FsKCdMYXRvIEl0YWxpYycpLCBsb2NhbCgnTGF0by1JdGFsaWMnKSwgdXJsKGh0dHBzOi8vZm9udHMuZ3N0YXRpYy5jb20vcy9sYXRvL3YxMS9McW93UURzbEd2NERtVUJBZldhMlZ3LnR0ZikgZm9ybWF0KCd0cnVldHlwZScpOwp9CkBmb250LWZhY2UgewogIGZvbnQtZmFtaWx5OiAnTGF0byc7CiAgZm9udC1zdHlsZTogaXRhbGljOwogIGZvbnQtd2VpZ2h0OiA3MDA7CiAgc3JjOiBsb2NhbCgnTGF0byBCb2xkIEl0YWxpYycpLCBsb2NhbCgnTGF0by1Cb2xkSXRhbGljJyksIHVybChodHRwczovL2ZvbnRzLmdzdGF0aWMuY29tL3MvbGF0by92MTEvSGtGX3FJMXhfbm94bHhocmhNUVlFS0NXY3luZl9jRHhYd0NMeGlpeEcxYy50dGYpIGZvcm1hdCgndHJ1ZXR5cGUnKTsKfQo=');

which will cause error in Chrome (I've not tried other browsers yet):

Resource interpreted as Stylesheet but transferred with MIME type application/octet-stream

Replace data:application/octet-stream with data:text/css fixed this issue.

Anyway thanks for this project! 😄

Add option for custom regexp

Add regexp options which change rImages. It useful if you need to inline specific files. F.e. You store a small interface images in assets folders in project, but big images you storage in files folder or on remote servers. Then you need specified that images must be inline only from assets folders

Commented code also being processed

For example i have a style.css file with code

/*
.first{
    background: url("../image1.png");
}*/

.second {
    background: url("../image2.jpg");
}

This plugin will also process image1.png and convert it to base64,
I know one can ignore by adding /*base64:skip*/, but commented code should not be processed.
Please fix this, thanks.

'gulp-css-base64' is not in the npm registry

$ npm install --save-dev gulp-css-base64
npm ERR! 404 404 Not Found: gulp-css-base64
npm ERR! 404 
npm ERR! 404 'gulp-css-base64' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it

css files were broken when processing multi files.

When I was using this plugin to process many css files, I found sometimes several file were broken:

For example:

/*a.css*/

.foo{
  background: url(/xx.jpg);
}

.bar {
   color: red;
}

after process, it become:

   color: red;
}

Or even worse.

I've been debugged it for several hours. And finally find out that it was caused by rImages.lastIndex :

rImages is a shared variable between different files' procedures. And async.whilst were used for async reading images. So unfortunately, sometimes, the following bug will appear: (for instance)

  1. a.css was processing. There is a image a.jpg to be read. And rImages.lastIndex was X.
  2. During the reading of a.jpg, b.css began to process. And rImages.lastIndex became Y.
  3. When a.jpg had been read, and the processing flow was back to a.css, as rImages.lastIndex got changed, things lost controll. a.css would be broken.

I've tried to optimized the code and got a temporary solution: https://gist.github.com/Clarence-pan/17798221f90ef6014a7adf1b7c55fc93

Make location configurable

location = path.join(path.dirname(file.path), result[1]);

would be better off with something like

location = options.location || path.join(path.dirname(file.path), result[1]);

because I have images stored somewhere else.

Does this work with Sass .scss files?

Sass doesn't fix relative urls so I tried running my .scss file through this before sass-compiling, but it doesn't work (the url stays the same). Sass is very similar to CSS so I expected it to work.

Preprocess functionality

It would be great to preprocess files before they're encoded, a little bit how Browserify does it: https://github.com/substack/node-browserify#btransformopts-tr

I would use it for compressing assets. Here's an example:

gulp.task("scss", function() {
  gulp.src("./index.scss")
    .pipe(sass())
    .pipe(cssBase64({
      preprocess: function(file) {
        return compress(file);
      }
    }))
    .pipe(gulp.dest("./dist"));
});

This saves having to write out a temporary directory with pre-minified assets. A more flexible alternative to options.deleteAfterEncoding.

No Base64 Conversation when scss files got included

Base64 conversation doesn't work if scss file got included in another file.

File structure

code_2018-09-12_16-19-12

sub/sub.scss

.my-image {
    background: url(sprite/9_2018_ohne.jpg);
}

test.scss

@import "sub/sub";

gulpfile

/// <binding ProjectOpened='sass, sass-watch' />
const gulp = require("gulp"),
  rename = require("gulp-rename"),
  sass = require("gulp-sass"),
  cleanCSS = require("gulp-clean-css"),
  sourcemaps = require("gulp-sourcemaps"),
  noop = require("gulp-noop"),
  header = require("gulp-header"),
  cssBase64 = require("gulp-css-base64");

const srcFolder = "src";
const productionBuild = false;

let bundle = {
  sassFiles: [`src/test.scss`],
  output: {
    file: "main.css",
    folder: "."
  }
};
let cleanCssOptions = {
  compatibility: "ie11",
  debug: true,
  level: 2
};

gulp.task("css", () => {
  let headerNotice = `/* test*/`;

  return gulp
    .src(bundle.sassFiles)
    .pipe(productionBuild ? noop() : sourcemaps.init())
    .pipe(sass())
    .pipe(
      cssBase64({
        //baseDir: "img",
        maxWeightResource: 100000000000
      })
    )
    .pipe(
      productionBuild ? cleanCSS(cleanCssOptions) : noop()
    )

    .pipe(rename(bundle.output.file))
    .pipe(productionBuild ? sourcemaps.write() : noop())
    .pipe(header(headerNotice))
    .pipe(gulp.dest(bundle.output.folder));
});

Generated css result:

.my-image {
  background: url(sprite/9_2018_ohne.jpg); }

If I place the background directive directly in test.scss it works well as expected:

.my-image {
  background: url(data:image/jpeg;base64, ...);

Installed Packages:

    "dependencies": {
        "gulp": "^3.9.1",
        "gulp-clean-css": "^3.9.4",
        "gulp-header": "^2.0.5",
        "gulp-noop": "^1.0.0",
        "gulp-rename": "^1.3.0",
        "gulp-sass": "^4.0.1",
        "gulp-sourcemaps": "^2.6.4"
    },
    "devDependencies": {
        "gulp-css-base64": "^1.3.4"
    }```

baseDir should accept absolute paths?

If processing multiple css files at the same time, in different folders, and i store all my fonts/images in a common folder, i cannot setup the basedir properly, since it will always be relative from the currently processed css.

Is this intended? in my case, i cannot pass any value that would process all files, wherever they are located in a common folder, without a common relative path to them.

deleteAfterEncoding option

First of all thanks for this plugin, very useful!
I was wondering if you could add option deleteAfterEncoding which would delete source images after embedding them in css? It would be very useful in many scenarios.
Thanks!

Handling file types with the `preProcess` option

How can we handle different file types with this option? The following works great for .svg but would fail if it encountered a file of another type. It might suffice to pass the MIME type or a file extension to the preProcess function. What do you think?

gulp.task("scss", function() {
  var svgo = new SVGO();
  return gulp.src("./lib/scss/index.scss")
    .pipe(sass())
    .pipe(cssBase64({
      baseDir: "../../",
      preProcess: function(buf, cb) {
        svgo.optimize(buf.toString("utf-8"), function(res) {
          cb(new Buffer(res.data));
        });
      }
    }))
    .pipe(gulp.dest("./dist"));
});

It might look something like this:

gulp.task("scss", function() {
  var svgo = new SVGO();
  return gulp.src("./lib/scss/index.scss")
    .pipe(sass())
    .pipe(cssBase64({
      baseDir: "../../",
      preProcess: function(ext, buf, cb) {
        switch (ext) {
          case "svg":
            svgo.optimize(buf.toString("utf-8"), function(res) {
              cb(new Buffer(res.data));
            });
            break;
          case "png":
            // Some PNG optimisation
            break;
          default:
            cb(buf);
        }
      }
    }))
    .pipe(gulp.dest("./dist"));
});

I'm not sure this is the cleanest way however. It's a tricky problem.

Bug: Urls ending with questionmark / hashtag are not base64 encoded

Urls ending with a questionmark / hashtag are not base64 encoded, see fontawesome

@font-face {
  font-family: 'FontAwesome';
  src: url('../fonts/fontawesome-webfont.eot?v=4.2.0');
  src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.2.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff?v=4.2.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.2.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.2.0#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.