Coder Social home page Coder Social logo

fetch / node-sass-asset-functions Goto Github PK

View Code? Open in Web Editor NEW
45.0 5.0 11.0 474 KB

Node SASS Asset functions

Home Page: https://npmjs.com/package/node-sass-asset-functions

License: MIT License

JavaScript 74.54% CSS 25.46%
node-sass grunt sass compass

node-sass-asset-functions's Introduction

Node SASS Asset functions Build Status npmjs

To ease the transitioning from Compass to Libsass, this module provides some of Compass' asset functions for node-sass

NB Please note that the functions option of node-sass is still experimental (>= v3.0.0).

Installation

npm install --save[-dev] node-sass-asset-functions

Usage

Basic usage is as easy as setting the functions property:

var sass = require('node-sass');
var assetFunctions = require('node-sass-asset-functions');

sass.render({
  functions: assetFunctions(),
  file: scss_filename,
  [, options..]
}, function(err, result) { /*...*/ });

You can specify the paths of your resources using the following options (shown with defaults):

{
  images_path: 'public/images',
  fonts_path: 'public/fonts',
  http_images_path: '/images',
  http_fonts_path: '/fonts'
}

So if for example your images reside in public/img instead of images/images, you use it as follows:

var sass = require('node-sass');
var assetFunctions = require('node-sass-asset-functions');

sass.render({
  functions: assetFunctions({
    images_path: 'public/img',
    http_images_path: '/img'
  }),
  file: scss_filename,
  [, options..]
}, function(err, result) { /*...*/ });

Additional options

asset_host: a function which completes with a string used as asset host.

sass.render({
  functions: assetFunctions({
    asset_host: function(http_path, done){
      done('http://assets.example.com');
      // or use the supplied path to calculate a host
      done('http://assets' + (http_path.length % 4) + '.example.com');
    }
  }),
  file: scss_filename,
  [, options..]
}, function(err, result) { /*...*/ });

asset_cache_buster: a function to rewrite the asset path

When this function returns a string, it's set as the query of the path. When returned an object, path and query will be used.

sass.render({
  functions: assetFunctions({
    asset_cache_buster: function(http_path, real_path, done){
      done('v=123');
    }
  }),
  file: scss_filename,
  [, options..]
}, function(err, result) { /*...*/ });
A more advanced example:

Here we include the file's hexdigest in the path, using the hexdigest module.

For example, /images/myimage.png would become /images/myimage-8557f1c9b01dd6fd138ba203e6a953df6a222af3.png.

var path = require('path')
  , fs = require('fs')
  , hexdigest = require('hexdigest');

sass.render({
  functions: assetFunctions({
    asset_cache_buster: function(http_path, real_path, done){
      hexdigest(real_path, 'sha1', function(err, digest) {
        if (err) {
          // an error occurred, maybe the file doesn't exists.
          // Calling `done` without arguments will result in an unmodified path.
          done();
        } else {
          var extname = path.extname(http_path)
            , basename = path.basename(http_path, extname);
          var new_name = basename + '-' + digest + extname;
          done({path: path.join(path.dirname(http_path), new_name), query: null});
        }
      });
    }
  }),
  file: scss_filename,
  [, options..]
}, function(err, result) { /*...*/ });

Available functions

  • image-url($filename: null, $only_path: false)
  • image-width($filename: null)
  • image-height($filename: null)
  • font-url($filename: null, $only-path: false)
  • font-files($filenames...)
  • and more to come

Usage with Grunt

Using this module with Grunt is just as easy:

var assetFunctions = require('node-sass-asset-functions');

module.exports = function(grunt){
  grunt.initConfig({
    // ...
    sass: {
      options: {
        functions: assetFunctions()
      },
      dist: {
        'public/stylesheets/application.css': 'app/assets/stylesheets/application.css.scss'
      }
    }
    // ...
  });
};

See also

node-sass-css-importer: Import CSS files into node-sass, just like sass-css-importer did for Compass

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

node-sass-asset-functions's People

Contributors

f0urfingeredfish avatar koenpunt avatar markplewis 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

Watchers

 avatar  avatar  avatar  avatar  avatar

node-sass-asset-functions's Issues

node-sass v4 compatibility

I'm using node-sass-asset-functions in one of my projects. When I upgrade node-sass to version 4.0.0 or higher, I get the following errors in my console, when I compile my .scss files:

undefined:0
TypeError: undefined is not a function
Segmentation fault: 11

I see that node-sass-asset-functions is using "node-sass": "^3.2.0" in its package.json. Are you planning to upgrade to version 4?

Allow relative assets

I ended up writing my own custom function to produce relative asset urls. It is possible due to this.options.file โ€“ the filepath of the Sass file being rendered โ€“ being available inside the function.

I will figure out how to apply it to this repo and submit a pull-request. In the meantime, the code is pasted below and an example project is available at https://github.com/henrahmagix/node-sass-relative-asset-url

Related to #5


var assetUrl = function (type, $assetPath) {
    var assetsPathForType = {
        image: 'app/media/images',
        font: 'app/media/fonts'
    };
    if (!assetsPathForType[type]) {
        throw new Error(`assetUrl: type ${type} not supported, must be one of ${Object.keys(assetsPathForType)}`);
    }
    var assetPath = $assetPath.getValue();
    var sassFilepath = this.options.file;
    // Since sassFilepath is a file, we need to normalise for
    // directory relations.
    var relativeToStylesRoot = path.relative(path.dirname(sassFilepath), 'sass');
    var stylesRootToAssets = path.relative('app/styles', assetsPathForType[type]);
    var stylesToAssetpath = path.join(relativeToStylesRoot, stylesRootToAssets, assetPath);
    var urlString = `url('${stylesToAssetpath}')`;
    return new sassTypes.String(urlString);
};

gulp.task('sass', () => {
    return gulp.src('sass/**/*.sass')
        .pipe(sass({
            functions: {
                'image-url($filepath)': function ($filepath) {
                    return assetUrl.call(this, 'image', $filepath);
                },
                'font-url($filepath)': function ($filepath) {
                    return assetUrl.call(this, 'font', $filepath);
                }
            }
        }).on('error', sass.logError))
        .pipe(gulp.dest('app/styles'));
});

Input

// main.sass
body
    background-image: image-url('myimage.png')
// nested/nested.sass
.nested
    background-image: image-url('nested/mynestedimage.png')

Output

/* main.css */
body {
  background-image: url('../media/images/myimage.png'); }
/* nested/nested.css */
.nested {
  background-image: url('../../media/images/nested/mynestedimage.png'); }

inline-image throws off sourcemaps

If you use inline-image, it tends to throw off source-maps. This may be a bug in node-sass, not this package.

EDIT: Discovered a work-around: set the sourceMapEmbed flag to true.

font-url() & image-url() return backslash'd paths when building on Windows

When building on a windows machine, the paths produced by image-url and font-url functions return paths with backslashes, rather than paths with forward slashes.
Normally this would be great, however when these paths are resolved by the browser the backslashes are encoded, and when it attempts to resolve those paths, a 404 is returned.

There may be a workaround for this that I'm not seeing, but I think requiring 'path-posix' in place of 'path' would resolve the problem.

Would be happy to submit a pull request - obviously testing would require a windows environment.

Please let me know what you think.

Support `url()` syntax for asset hashing

One suggestion is to support url() for asset_cache_buster. Then this could also be used for an asset hashing tool regardless of compass migration.

Use case:

We have a file hashmap.json hash map that we generate on build that tells the backend / frontend where to find the files.

{
  "images/image.png": "/static/fd9a859f1205a0b5d5b2d6c9f28aee0f274cd4d9/images/image.png"
}

Then in grunt I am using your plugin like:

assetHashMap = JSON.parse(fs.readFileSync('hashmap.json'));

[...]

  sass: {
    options: {
      functions: assetFunctions({
        asset_cache_buster: function(http_path, real_path, done) {
          var hash_path;
          hash_path = assetHashMap[http_path];
          return done({
            path: hash_path,
            query: null
          });
        }
      })
    }
  }

In my Sass I am calling the image like:

body {
  background: image-url('image.png');
}

This works great! But, it would be awesome if I could migrate off of compass syntax entirely and use url(), like this:

body {
  background: url('images/image.png');
}

I will try to fork and update if I can, but it may be something easy for the original developers to add if they feel it would be a nice addition.

I have found this tool to be very helpful in my transition from compass to node-sass. Thank you.

Supporting option for dart-sass ? ( or drop node-sass as dependency )

Maybe it could be solved by making a fork (since this package is **node-sass-**asset-functions )


Some people are now using dart-sass (or sass ) instead of node-sass, because of the painfulness caused by the native extension :(

Like sass-loader made itself sass-implementation-agnostic, it would be great to make node-sass-asset-functions also implementation-agnostic.

I found that node-sass-asset-functions itself runs well with sass, but even when I don't need node-sass as dependency, install node-sass-asset-functions forces my machine to rebuild node-sass.

2018-09-12 23 35 19

How it should be like?

Taking sass module as a parameter

assetFunctions({
    ....
    implementation: require('node-sass') // or require('sass')
})

// or even...
assetFunctionsFor(require('node-sass'))({
    ....
})

Then drop node-sass from dependencies, and it allows users to avoid forced rebuilding node-sass.

Tests stuck

I try to run tests with jest testrunner but it seems they don't work correctly.
They just stuck at:
$ ./node_modules/.bin/jest

Using:
node: 4.7.0
jest: latest

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.