Creating Module Functions
One of Sassport's main features is bridging JavaScript functions to be used in Sass files. This is done by passing in the function signature and function as a key-value pair in the .functions({ ... })
method:
const fooModule = sassport.module('foo')
.functions({
'greet($val)': (val) => {
return sass.types.String('Hello, ' + val.getValue());
}
);
This is done in the same way as defining custom functions in Node-Sass, where special Sass value instances are returned. This can be useful when you need to know certain things about the value, e.g., units of a length.
In Sassport, sassport.utils
provides Chris Eppstein's excellent node-sass-utils library to make it easier to work with Sass values in JavaScript.
Wrapping functions
Often, however, you do not need to know that meta-data, and you would rather pass the value directly to JavaScript, as a JavaScript value. When that's the case, you can wrap the function in sassport.wrap(fn, options)
:
const fooModule = sassport.module('foo')
.functions({
'greet($val)': sassport.wrap((val) => {
return 'Hello, ' + val;
})
);
Wrapping libraries
Entire libraries/modules can be wrapped using sassport.wrapAll(lib, options)
. The library is expected to be an object/Class instance with methods and/or properties. The arguments passed into the resulting Sass function (e.g., Math($key, $args...)
are:
$key
- the key in the library to be retrieved$args...
- (optional) any arguments to be passed to the function, if the key represents a method/function.
For example, here's how the entire JavaScript native Math
library can be wrapped:
// Sample math module
export default sassport.module('js-math')
.functions({
'Math($key, $args...)': sassport.wrapAll(Math)
});
// index.js
import sassport from 'sassport';
import spMath from './path/to/js-math-module';
sassport([ spMath ])
.render({
file: 'main.scss'
}, (err, result) => {
console.log(result.css.toString());
});
// main.scss
$PI: Math(PI);
// => 3.14159...
$two-squared: Math(pow, 2, 2);
// => 4
$cos-test: Math(cos, 2 * $PI);
// => 1
Inferring Types
With the sassport.wrap(fn, options)
utility function, normal JS functions can be wrapped to automatically have arguments converted to JS values, and to automatically have the JS return value converted to Sass values using this conversion:
Number (Sass)
- converted to a unitless JS number.Number (JS)
- converted to a unitless Sass number.String (Sass)
- converted to a JS string.String (JS)
- converted to an unquoted Sass string, unless{quotes: true}
is specified for theoptions
object.List (Sass)
- converted to a JS array.Array (JS)
- converted to a Sass list.Map (Sass)
- converted to a JS map-like object, with.get(key)
and.set(key, value)
methods.Object (JS)
- converted to a Sass map.Bool (Sass)
- converted to a JS boolean.Boolean (JS)
- converted to a Sass boolean.Null (Sass)
- converted to a JSnull
value.null (JS)
- converted to a Sassnull
value.