A Browserify transform for bundling, rebasing, inlining, and minifying CSS files. It's useful for CSS modularization where styles are scoped to their related bundles.
Getting StartedIf you're new to browserify, check out the browserify handbook and the resources on browserify.org.
Installationnpm install --save-dev browserify-css
app.css:
@import url("modules/foo/index.css");
@import url("modules/bar/index.css");
body {
    background-color: #fff;
}
app.js:
var css = require('./app.css');
console.log(css);
You can compile your app by passing -t browserify-css to browserify:
$ browserify -t browserify-css app.js > bundle.js
Each require('./path/to/file.css')
call will concatenate CSS files with @import statements, rebasing urls, inlining @import, and minifying CSS. It will add a style tag with an optional data-href attribute to the head section of the document during runtime:
Configuration<html>
<head>
    <style type="text/css" data-href="app.css">...</style>
</head>
</html>
You can set configuration to your package.json file:
{
    "browserify-css": {
        "autoInject": true,
        "minify": true,
        "rootDir": "."
    }
}
or use an external configuration file like below:
{
    "browserify-css": "./config/browserify-css.js"
}
config/browserify-css.js:
module.exports = {
    "autoInject": true,
    "minify": true,
    "rootDir": "."
};
Furthermore, browserify-css transform can obtain options from the command-line with subarg syntax:
$ browserify -t [ browserify-css --minify=true --output bundle.css ] -o bundle.js app.js
or from the api:
b.transform('browserify-css', {
minify: true,
output: 'bundle.css'
});
Options autoInject
Type: Boolean
Default: true
If true, each require('path/to/file.css')
call will add a style tag to the head section of the document.
Type: Object
Default:
{
    "verbose": true,
    "insertAt": "bottom"Â
}
verbose
If verbose is set to true, the path to CSS will be specified in the data-href attribute inside the style tag
insertAt
By default, browserify-css transform appends <style> elements to the end of the <head> tag of the page. This will cause CSS created by browserify-css transform to take priority over CSS already present in the document head. To insert style elements at the beginning of the head, set the insertAt parameter to 'top'.
inlineImagesType: Boolean
or Object
Default: false
If true, each required css file will have image url()
replaced with data urls. For example from:
  background-image: url("background.png");
to:
inlineImagesOptions  background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAVQAAAHgCAYAAAD6yZXWAAAABmJLR0QA");
Type: Object
Default:
{
   Â
    "limit": 0Â
}
If a limit is set, then only files that are smaller than the number of bytes given will be inlined into the css file.
minifyType: Boolean
Default: false
Type: Object
Default: {}
Check out a list of CSS minify options at CleanCSS.
onFlushType: Function
The onFlush
option accepts a function which takes two arguments: (options, done).
onFlush: function(options, done) {
   Â
   Â
    done();
   Â
   Â
   Â
    done(null);
   Â
   Â
   Â
    done('module.exports = ' + JSON.stringify(options.data) + ';');
}
You can use the onFlush
option to output each CSS to a separate file, or append multiple CSS into one file. For example:
outputvar browserify = require('browserify');
var fs = require('fs');
Â
fs.unlinkSync('dist/assets/app.css');
Â
browserify(options)
    .add('src/index.js')
    .transform(require('browserify-css'), {
        rootDir: 'src',
        onFlush: function(options, done) {
            fs.appendFileSync('dist/assets/app.css', options.data);
           Â
           Â
            done(null);
        }
    })
    .bundle();
Type: String
Default: ''
The output path of the CSS file. When using this option, browserify-css will not embed stylesheets into a JavaScript bundle.
processRelativeUrlbrowserify -t [ browserify-css --minify=true --output bundle.css ] -o bundle.js index.js
Type: Function
The processRelativeUrl
option accepts a function which takes one argument (the relative url) and returns the original relativeUrl
string or the converted result. For example:
var browserify = require('browserify');
Â
browserify(options)
    .add('src/index.js')
    .transform(require('browserify-css'), {
        rootDir: 'src',
        processRelativeUrl: function(relativeUrl) {
            return relativeUrl;
        }
    })
    .bundle();
You can embed the image data directly into the CSS file with data URI, like so:
var _ = require('lodash');
var path = require('path');
var browserify = require('browserify');
Â
browserify(options)
    .add('src/index.js')
    .transform(require('browserify-css'), {
        rootDir: 'src',
        processRelativeUrl: function(relativeUrl) {
            if (_.contains(['.jpg','.png','.gif'], path.extname(relativeUrl))) {
               Â
                var DataUri = require('datauri');
                var dUri = new DataUri(relativeUrl);
                return dUri.content;
            }
            return relativeUrl;
        }
    })
    .bundle();
You may also want to check out the FAQ for advanced usage.
rebaseUrlsType: Boolean
Default: true
If true, relative paths will be rebased in css files; if false, paths will be unchanged.
rootDirType: String
Default: ./
An absolute path to resolve relative paths against the project's base directory.
stripCommentsType: Boolean
Default: false
Strip comments from CSS. Defaults to false.
FAQ 1. How do I include CSS files located inside the node_modules folder?You can choose one of the following methods to include CSS files located inside the node_modules folder:
@import
rule. For example:app.js:
require('./app.css');
app.css:
@import "node_modules/foo/foo.css";
Â
@import "styles/common.css";
--global-transform
or -g
) on the command line to transform all files in a node_modules directory:$ browserify -g browserify-css app.js > bundle.jsÂ
or use the API directly:
var browserify = require('browserify');
var b = browserify('./app.js');
b.transform('browserify-css', {global: true});
b.bundle().pipe(process.stdout);
See browserify transform options for details.
Then you will be able to require CSS files from within node_modules. For example:
require('bootstrap/dist/bootstrap.css');
node_modules
directory on a per-module basis like so:node_modules/foo/package.json:
{
  "browserify": {
    "transform": ["browserify-css"]
  }
}
Then, run browserify transform on the command line:
2. How do I load font and image files from node_modules?$ browserify -t browserify-css app.js > bundle.jsÂ
Assume that you have the following directory structure:
package.json
dist/
src/
    index.js
    index.css
node_modules/
    bootstrap/
        dist/
            css/
                bootstrap.css
The index.css
uses @import
to import external style sheets:
@import url("../node_modules/bootstrap/dist/css/bootstrap.css");
All output files, including the generated bundle.js
, are created under the dist
directory:
dist/
    bundle.js
    vendor/
        bootstrap/
            dist/
                css/
                    bootstrap.css
Suppose that the dist
directory is your web root, you might want to copy external font and images files from ../node_modules/
to dist/vendor/
.
For example, the @font-face
rules in node_modules/bootstrap/dist/css/bootstrap.css
:
@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),
         url('../fonts/glyphicons-halflings-regular.woff2') format('woff2'),
         url('../fonts/glyphicons-halflings-regular.woff') format('woff'),
         url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'),
         url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}
The example below illustrates the use of the processRelativeUrl
option:
Acknowledgementsvar gulp = require('gulp');
var gutil = require('gulp-util');
var path = require('path');
var browserify = require('browserify');
var sourceStream = require('vinyl-source-stream');
var fse = require('fs-extra');
Â
var bundleStream = browserify()
    .add('src/index.js')
    .transform(require('browserify-css'), {
        rootDir: 'src',
        processRelativeUrl: function(relativeUrl) {
            var stripQueryStringAndHashFromPath = function(url) {
                return url.split('?')[0].split('#')[0];
            };
            var rootDir = path.resolve(process.cwd(), 'src');
            var relativePath = stripQueryStringAndHashFromPath(relativeUrl);
            var queryStringAndHash = relativeUrl.substring(relativePath.length);
Â
           Â
           Â
           Â
            var prefix = '../node_modules/';
            if (_.startsWith(relativePath, prefix)) {
                var vendorPath = 'vendor/' + relativePath.substring(prefix.length);
                var source = path.join(rootDir, relativePath);
                var target = path.join(rootDir, vendorPath);
Â
                gutil.log('Copying file from ' + JSON.stringify(source) + ' to ' + JSON.stringify(target));
                fse.copySync(source, target);
Â
               Â
                return vendorPath + queryStringAndHash;
            }
Â
            return relativeUrl;
        }
    })
    .bundle();
Â
bundleStream
    .pipe(sourceStream(bundleFile))
    .pipe(gulp.dest(browserifyConfig.dest));
Â
Test Images:
test/fixtures/background.png
Originally by W3C under terms of CC-BY-3.0, via Wikimedia Commons
test/fixtures/background-600.png
Originally by Rudloff under terms of CC-BY-3.0, via Wikimedia Commons
MIT
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4