### Compile SCSS in Browser Synchronously
Source: https://github.com/medialize/sass.js/blob/master/docs/getting-started.md
This snippet shows how to use the synchronous API of Sass.js in a browser by including `dist/sass.sync.js`. This approach compiles SCSS directly in the main thread and is not recommended for general use due to potential performance implications. It exposes a singleton instance for compilation.
```html
```
--------------------------------
### Prepare and Install Sass.js Repository
Source: https://github.com/medialize/sass.js/blob/master/docs/build.md
This snippet outlines the initial steps to set up the Sass.js project. It involves cloning the repository, navigating into the project directory, and installing the necessary Node.js dependencies.
```bash
clone git@github.com:medialize/sass.js.git
cd sass.js
npm install
```
--------------------------------
### Compile SCSS in Node.js Synchronously
Source: https://github.com/medialize/sass.js/blob/master/docs/getting-started.md
This example demonstrates compiling SCSS code within a Node.js environment using the synchronous API of Sass.js. It requires the `sass.js` module and then uses the `Sass.compile` method to process an SCSS string, logging the output. This is suitable for server-side operations where Web Workers are not available or necessary.
```javascript
var Sass = require('sass.js');
var scss = '$someVar: 123px; .some-selector { width: $someVar; }';
Sass.compile(scss, function(result) {
console.log(result);
});
```
--------------------------------
### Compile SCSS Files from File System in Node.js
Source: https://github.com/medialize/sass.js/blob/master/docs/getting-started.md
This snippet utilizes the `sass.node.js` utility for compiling SCSS files directly from the file system in a Node.js environment. It requires the `sass.js/dist/sass.node` module, which provides a convenient API for file I/O and compilation. The example shows how to specify a file path, optional compilation options, and a callback to handle the compilation result.
```javascript
var compile = require('sass.js/dist/sass.node');
var path = 'scss/example.scss';
var options = {
style: compile.Sass.style.expanded,
};
compile(path, options, function(result) {
console.log(result);
});
```
--------------------------------
### Compile SCSS in Browser using Web Worker
Source: https://github.com/medialize/sass.js/blob/master/docs/getting-started.md
This snippet demonstrates how to use Sass.js in a web browser with a Web Worker. It includes the Sass.js library and then compiles a given SCSS string, logging the result to the console. This is the recommended approach for browser usage as it avoids blocking the main thread.
```html
```
--------------------------------
### Example Sass File Import within Emscripten File System
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Demonstrates how to compile Sass code that imports other Sass files previously registered in the emscripten file system using `writeFile`. This example shows importing 'one.scss' and 'some-dir/two.scss'.
```javascript
var sass = new Sass();
sass.writeFile('one.scss', '.one { width: 123px; }');
sass.writeFile('some-dir/two.scss', '.two { width: 123px; }');
sass.compile('@import "one"; @import "some-dir/two";', function(result) {
console.log(result.text);
});
```
--------------------------------
### Sequential Sass Compilation Example
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Demonstrates the default sequential compilation behavior of Sass.js, where multiple compile calls are processed one after another. An instance of Sass is created pointing to the worker script.
```javascript
// compile sources in sequence (default behavior)
var sass = new Sass('path/to/sass.worker.js');
sass.compile(source1, callback1);
sass.compile(source2, callback2);
```
--------------------------------
### Configure Sass.js Worker URL with Module Loader
Source: https://github.com/medialize/sass.js/blob/master/docs/getting-started.md
When using Sass.js with a module loader like RequireJS or Browserify, you need to explicitly set the worker URL. This ensures Sass.js can locate its worker script, `sass.worker.js`, which is essential for its operation in the browser. After setting the worker URL, you can initialize Sass.js and compile SCSS as usual.
```javascript
define(function defineSassModule(require) {
// load Sass.js
var Sass = require('path/to/sass.js');
// tell Sass.js where it can find the worker,
// url is relative to document.URL - i.e. outside of whatever
// Require or Browserify et al do for you
Sass.setWorkerUrl('path/to/dist/sass.worker.js');
// initialize a Sass instance
var sass = new Sass();
var scss = '$someVar: 123px; .some-selector { width: $someVar; }';
sass.compile(scss, function(result) {
console.log(result);
});
});
```
--------------------------------
### Node.js Filesystem Compilation with Sass.js
Source: https://context7.com/medialize/sass.js/llms.txt
Compiles SCSS files directly from the real filesystem within a Node.js environment. It utilizes the `sass.js/dist/sass.node` module and allows configuration of compilation options such as output style and precision. This requires the `sass.js` package to be installed.
```javascript
var compile = require('sass.js/dist/sass.node');
var path = 'scss/main.scss';
var options = {
style: compile.Sass.style.expanded,
precision: 5,
sourceMapEmbed: false
};
compile(path, options, function(result) {
if (result.status === 0) {
console.log('CSS output:', result.text);
console.log('Source map:', result.map);
console.log('Imported files:', result.files);
} else {
console.error('Compilation error:');
console.error(result.formatted);
// Error: invalid top-level expression
// on line 7 of stdin
// >> bad-token-test
// ^
}
});
```
--------------------------------
### Sass.js Importer Callback Example (JavaScript)
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
This snippet demonstrates how to register and use a custom importer callback in Sass.js to intercept and handle `@import` declarations. The callback receives a request object detailing the import path and options, and must call `done()` with a result object containing the resolved path, content, or an error.
```javascript
sass.importer(function(request, done) {
// (object) request
// (string) request.current path libsass wants to load (content of »@import "";«)
// (string) request.previous absolute path of previously imported file ("stdin" if first)
// (string) request.resolved currentPath resolved against previousPath
// (string) request.path absolute path in file system, null if not found
// (mixed) request.options the value of options.importer
// -------------------------------
// (object) result
// (string) result.path the absolute path to load from file system
// (string) result.content the content to use instead of loading a file
// (string) result.error the error message to print and abort the compilation
// asynchronous callback
done(result);
});
```
```javascript
// register a custom importer callback
sass.importer(function(request, done) {
if (request.path) {
// Sass.js already found a file,
// we probably want to just load that
done();
} else if (request.current === 'content') {
// provide a specific content
// (e.g. downloaded on demand)
done({
content: '.some { content: "from anywhere"; }'
})
} else if (request.current === 'redirect') {
// provide a specific content
done({
path: '/sass/to/some/other.scss'
})
} else if (request.current === 'error') {
// provide content directly
// note that there is no cache
done({
error: 'import failed because bacon.'
})
} else {
// let libsass handle the import
done();
}
});
// unregister custom reporter callback
sass.importer(null);
```
--------------------------------
### List Files with Sass.js
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Illustrates how to retrieve a list of all registered files, regardless of their directory structure, using the `sass.listFiles` method. The method accepts a callback that receives an array of file paths.
```javascript
// list all files (regardless of directory structure)
sass.listFiles(function callback(list) {
// (array) list contains the paths of all registered files
});
```
--------------------------------
### Prepare and Build Libsass.js
Source: https://github.com/medialize/sass.js/blob/master/docs/build.md
This sequence of commands focuses on building only the libsass.js part of the project. It first prepares the libsass repository and then invokes Emscripten to compile the C/C++ code into JavaScript. This is useful when primarily working on the C wrapper.
```bash
npm run libsass:prepare
npm run libsass:build
```
--------------------------------
### Preloading Files
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Downloads a specified set of files immediately and makes them available to Sass.js.
```APIDOC
## Preloading Files
### `sass.preloadFiles(base, directory, files, callback)`
**Description**: Downloads a set of files immediately and makes them available to Sass.js. This operation is asynchronous.
**Method**: `sass.preloadFiles`
**Parameters**:
#### Path Parameters
- **base** (string) - Required - The base URL or path from which to download files. HTTP requests are made relative to this.
- **directory** (string) - Required - The directory within the `base` where the files are located. Can be an empty string.
- **files** (array) - Required - An array of file names to preload. These are relative to both `base` and `directory`.
#### Callback Function
- **callback** (function) - Required - A function that is called when the preloading operation is completed. It is invoked without arguments.
### Request Example
```javascript
var base = '../scss/';
var directory = '';
var files = [
'demo.scss',
'example.scss',
'_importable.scss',
'deeper/_some.scss'
];
sass.preloadFiles(base, directory, files, function() {
console.log('Files preloaded successfully.');
});
```
```
--------------------------------
### Listing Files
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Retrieves a list of all registered files in the Sass.js environment.
```APIDOC
## Listing Files
### `sass.listFiles(callback)`
**Description**: Lists all files currently registered in the Sass.js file system, regardless of their directory structure.
**Method**: `sass.listFiles`
**Parameters**:
#### Callback Function
- **callback** (function) - Required - A function that is called with the list of files.
- **list** (array) - An array containing the paths of all registered files.
### Request Example
```javascript
sass.listFiles(function(list) {
console.log('Registered files:', list);
});
```
```
--------------------------------
### Sass.js Sync: Write File and Compile
Source: https://github.com/medialize/sass.js/blob/master/sass.sync.html
Demonstrates writing Sass files asynchronously and then compiling them. This is useful for setting up the Sass environment with custom imports and rules before generating CSS. It requires the Sass.js library to be loaded.
```javascript
Sass.writeFile('testfile.scss', '@import "sub/deeptest";\n.testfile { content: "loaded"; }', function() {
console.log('wrote "testfile.scss"');
});
Sass.writeFile('sub/deeptest.scss', '.deeptest { content: "loaded"; }', function() {
console.log('wrote "sub/deeptest.scss"');
});
Sass.options({ style: Sass.style.expanded }, function(result) {
console.log("set options");
});
Sass.compile('@import "testfile";', function(result) {
console.log("compiled", result.text);
});
```
--------------------------------
### Build Sass.js
Source: https://github.com/medialize/sass.js/blob/master/docs/build.md
This command compiles the Sass.js library, generating several output files in the `dist` directory. These files include the main JavaScript library, Node.js specific versions, synchronous and worker versions, and version information.
```bash
npm run build
```
--------------------------------
### Load Sass.js Source Files in Browser
Source: https://github.com/medialize/sass.js/blob/master/docs/build.md
This HTML snippet demonstrates how to load and use Sass.js directly from its source files in a web browser. It requires pre-compiling libsass.js and then includes script tags for various Sass.js components before initializing and compiling SCSS.
```html
```
--------------------------------
### Preload Files Asynchronously with Sass.js
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Explains how to use `Sass.preloadFiles()` to immediately download a set of registered files. This method makes HTTP requests relative to a provided base URL and directory, and is suitable for asynchronous operations.
```javascript
// HTTP requests are made relative to worker
var base = '../scss/';
// equals 'http://medialize.github.io/sass.js/scss/'
// the directory files should be made available in
var directory = '';
// the files to load (relative to both base and directory)
var files = [
'demo.scss',
'example.scss',
'_importable.scss',
'deeper/_some.scss',
];
// preload a set of files
sass.preloadFiles(base, directory, files, function callback() {
// invoked without arguments when operation completed
});
```
--------------------------------
### Initialize and Destroy Sass Worker Instance
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Demonstrates how to initialize a Sass.js worker instance and subsequently destroy it. The worker URL can be set globally to avoid repeated specification.
```javascript
// initialize a Sass instance
var sass = new Sass('path/to/sass.worker.js');
// destruct/destroy/clean up a Sass instance
sass.destroy();
```
```javascript
// globally set the URL where the the sass worker file is located
// so it does not have to be supplied to every constructor
Sass.setWorkerUrl('path/to/sass.worker.js');
var sass = new Sass();
```
--------------------------------
### Register Multiple Sass Files
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Allows registering multiple Sass files simultaneously into the emscripten file system. This method takes an object where keys are file paths and values are their source content, and returns a result object detailing the success of each write operation.
```javascript
sass.writeFile({
'file-1.scss': 'source-1',
'directory/file-2.scss': 'source-2',
}, function callback(result) {
// (object) result is
// result['file-1.scss']: success
// result['directory/file-2.scss']: success
// (boolean) success is
// `true` when the write was OK,
// `false` when it failed
});
```
--------------------------------
### Clear All Files with Sass.js
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Shows how to clear all registered files from Emscripten's file system using the `sass.clearFiles` method. This method takes a callback that is invoked upon completion.
```javascript
// remove all files
sass.clearFiles(function callback() {
// invoked without arguments when operation completed
});
```
--------------------------------
### Parallel SCSS Compilation with Sass.js Workers
Source: https://context7.com/medialize/sass.js/llms.txt
Demonstrates how to compile multiple SCSS sources concurrently using separate Sass.js worker instances. Ensure the worker script 'dist/sass.worker.js' is correctly set.
```javascript
// Set worker URL once
Sass.setWorkerUrl('dist/sass.worker.js');
// Create multiple instances for parallel compilation
var sass1 = new Sass();
var sass2 = new Sass();
var sass3 = new Sass();
var sources = [
'$color1: red; .box1 { color: $color1; }',
'$color2: blue; .box2 { color: $color2; }',
'$color3: green; .box3 { color: $color3; }'
];
// Compile in parallel
sass1.compile(sources[0], function(result) {
console.log('Result 1:', result.text);
sass1.destroy();
});
sass2.compile(sources[1], function(result) {
console.log('Result 2:', result.text);
sass2.destroy();
});
sass3.compile(sources[2], function(result) {
console.log('Result 3:', result.text);
sass3.destroy();
});
```
--------------------------------
### Reset Sass.js to Default Options
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Shows how to reset all Sass.js compilation options back to their default values using the 'defaults' option.
```javascript
// reset options to Sass.js defaults (listed above)
sass.options('defaults', function callback() {
// invoked without arguments when operation completed
});
```
--------------------------------
### Parallel Sass Compilation with Worker API
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Shows how to achieve parallel Sass compilation using the Worker API. Multiple Sass instances are created and initialized after setting the worker URL, allowing concurrent compilation of sources.
```javascript
Sass.setWorkerUrl('path/to/sass.worker.js')
var sass1 = new Sass();
var sass2 = new Sass();
sass1.compile(source1, callback1);
sass2.compile(source2, callback2);
```
--------------------------------
### Remove Files with Sass.js
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Demonstrates how to remove single or multiple files using the `sass.removeFile` method. It takes a file path or an array of paths and a callback function that reports the success of the operation.
```javascript
// remove a file
sass.removeFile(path, function callback(success) {
// (boolean) success is
// `true` when deleting the file was OK,
// `false` when it failed
});
// remove multiple files
sass.removeFile([
path1,
path2,
], function callback(result) {
// (object) result is
// result[path1]: success
// result[path2]: success
// (boolean) success is
// `true` when deleting the file was OK,
// `false` when it failed
});
```
--------------------------------
### Configure Sass.js Syntax Mode
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Sets the option to determine whether the input source string should be treated as SASS or SCSS. `indentedSyntax: true` enables SASS.
```javascript
sass.options({
// Treat source_string as SASS (as opposed to SCSS)
indentedSyntax: false,
}, function callback() {
// invoked without arguments when operation completed
});
```
--------------------------------
### Sass.js Worker API Usage
Source: https://github.com/medialize/sass.js/blob/master/sass.worker.html
This JavaScript snippet demonstrates how to initialize the Sass.js worker, write SCSS files, configure compilation options, and compile SCSS to CSS. It uses an asynchronous callback pattern for file writing and compilation. Ensure the worker script is correctly located or set using Sass.setWorkerUrl.
```javascript
var sass = new Sass();
sass.writeFile('testfile.scss', '@import "sub/deeptest";\n.testfile { content: "loaded"; }', function() {
console.log('wrote "testfile.scss"');
});
sass.writeFile('sub/deeptest.scss', '.deeptest { content: "loaded"; }', function() {
console.log('wrote "sub/deeptest.scss"');
});
sass.options({ style: Sass.style.expanded }, function(result) {
console.log("set options");
});
sass.compile('@import "testfile";', function(result) {
console.log("compiled", result.text);
});
```
--------------------------------
### Initialize Sass.js Web Worker API
Source: https://context7.com/medialize/sass.js/llms.txt
Initializes a Sass instance using a Web Worker for non-blocking SCSS compilation in browser environments. It requires setting the worker URL globally and allows for asynchronous compilation, returning the compiled CSS or an error. The instance should be destroyed when no longer needed.
```javascript
// Set worker URL globally (once)
Sass.setWorkerUrl('dist/sass.worker.js');
// Initialize a new Sass instance
var sass = new Sass();
var scss = '$font-size: 16px; body { font-size: $font-size; }';
sass.compile(scss, function(result) {
if (result.status === 0) {
console.log(result.text);
} else {
console.error('Error:', result.formatted);
}
});
// Clean up when done
sass.destroy();
```
--------------------------------
### Configure Sass.js Output Style and Formatting
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Configures Sass.js compilation options related to output style, precision, comments, indentation, and line endings.
```javascript
sass.options({
// Format output: nested, expanded, compact, compressed
style: Sass.style.nested,
// Decimal point precision for outputting fractional numbers
// (-1 will use the libsass default, which currently is 5)
precision: -1,
// If you want inline source comments
comments: false,
// String to be used for indentation
indent: ' ',
// String to be used to for line feeds
linefeed: '\n',
}, function callback() {
// invoked without arguments when operation completed
});
```
--------------------------------
### Preload SCSS Files via HTTP using Sass.js
Source: https://context7.com/medialize/sass.js/llms.txt
Loads SCSS files from a base URL and a specified directory into Sass.js's virtual filesystem. This allows subsequent compilations to reference these preloaded files without needing to fetch them again. It requires the Sass.js library.
```javascript
var sass = new Sass();
var baseUrl = 'https://example.com/scss/';
var directory = 'vendor/';
var files = [
'normalize.scss',
'mixins/_breakpoints.scss',
'mixins/_flexbox.scss'
];
sass.preloadFiles(baseUrl, directory, files, function() {
console.log('Files preloaded');
// Now compile using the preloaded files
sass.compile('@import "vendor/normalize"; @import "vendor/mixins/flexbox";', function(result) {
console.log(result.text);
});
});
```
--------------------------------
### Compile Sass File with Options and Callback
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Compiles a Sass file with specific compilation options. This method allows overriding global Sass options for a single file compilation. It takes the file path, an options object, and a callback function that receives the result object.
```javascript
sass.compileFile(path, options, function callback(result) {
// invoked with the response object as single argument when operation completed
});
```
--------------------------------
### Compile SCSS File from Virtual Filesystem using Sass.js
Source: https://context7.com/medialize/sass.js/llms.txt
Compiles a SCSS file that has been written to or exists within Sass.js's virtual filesystem. This method supports compiling directly from a file path and allows for optional compilation settings like output style. It depends on the Sass.js library.
```javascript
var sass = new Sass();
// Write file first
sass.writeFile('app.scss', '$bg: #fff; body { background: $bg; }', function() {
// Compile the file (libsass auto-detects .scss vs .sass)
sass.compileFile('app.scss', function(result) {
if (result.status === 0) {
console.log(result.text);
console.log('Files used:', result.files);
}
});
// Compile with options
sass.compileFile('app.scss', { style: Sass.style.compressed }, function(result) {
console.log(result.text); // body{background:#fff}
});
});
```
--------------------------------
### Configure Sass.js Compilation Options
Source: https://context7.com/medialize/sass.js/llms.txt
Configures global compilation options for Sass.js, including output style, precision, source map settings, and indentation. It also demonstrates how to apply per-compilation options when calling the compile method. Options can be reset to defaults.
```javascript
var Sass = require('sass.js');
// Reset to defaults
Sass.options('defaults', function() {
console.log('Options reset');
});
// Set specific options
Sass.options({
style: Sass.style.compressed, // nested, expanded, compact, compressed
precision: 5, // Decimal precision for numbers
comments: false, // Include source comments
indent: ' ', // Indentation string
linefeed: '\n', // Line feed character
sourceMapEmbed: false, // Embed source map as data URI
sourceMapContents: true // Include source contents in map
}, function() {
console.log('Options configured');
});
// Compile with per-call options
var scss = '$width: 123.456789px; .box { width: $width; }';
Sass.compile(scss, { style: Sass.style.compressed, precision: 2 }, function(result) {
console.log(result.text); // .box{width:123.46px}
});
```
--------------------------------
### Lazyloading Files (DEPRECATED)
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Registers files to be loaded synchronously only when they are actually required by libsass. Note: This method is deprecated and may impact performance.
```APIDOC
## Lazyloading Files (DEPRECATED)
### `sass.lazyFiles(base, directory, files, callback)`
**Description**: Registers files to be loaded synchronously when they are required by libsass. This method is **deprecated** and **not available** in the synchronous API. It can slow down perceived performance due to synchronous HTTP requests.
**Method**: `sass.lazyFiles`
**Parameters**:
#### Path Parameters
- **base** (string) - Required - The base URL or path from which to download files. HTTP requests are made relative to this.
- **directory** (string) - Required - The directory within the `base` where the files are located. Can be an empty string.
- **files** (array) - Required - An array of file names to register. These are relative to both `base` and `directory`.
#### Callback Function
- **callback** (function) - Required - A function that is called when the registration operation is completed. It is invoked without arguments.
### Request Example
```javascript
var base = '../scss/';
var directory = '';
var files = [
'demo.scss',
'example.scss',
'_importable.scss',
'deeper/_some.scss'
];
sass.lazyFiles(base, directory, files, function() {
console.log('Files registered for lazy loading.');
});
```
```
--------------------------------
### Read Multiple Sass Files
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Reads the content of multiple Sass files from the emscripten file system concurrently. It accepts an array of file paths and returns an object containing the content for each requested file via a callback.
```javascript
sass.readFile([
path1,
path2,
], function callback(result) {
// (object) result is
// result[path1]: content
// result[path2]: content
// (string) content is the file's content,
// `undefined` when the read failed
});
```
--------------------------------
### Lazyload Files Synchronously with Sass.js (Deprecated)
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Describes the `Sass.lazyFiles()` method for registering files that are loaded synchronously only when required by libsass. Note that this method is deprecated and can impact performance due to sequential HTTP requests. It is not available in the synchronous API.
```javascript
// HTTP requests are made relative to worker
var base = '../scss/';
// equals 'http://medialize.github.io/sass.js/scss/'
// the directory files should be made available in
var directory = '';
// the files to load (relative to both base and directory)
var files = [
'demo.scss',
'example.scss',
'_importable.scss',
'deeper/_some.scss',
];
// register a set of files to be (synchronously) loaded when required
sass.lazyFiles(base, directory, files, function callback() {
// invoked without arguments when operation completed
});
```
--------------------------------
### Compile Sass File with Callback
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Compiles a Sass file from the emscripten file system to CSS. It accepts a file path and a callback function that is invoked upon completion with a result object. Libsass automatically detects SCSS or SASS based on file extension.
```javascript
sass.compileFile(path, function callback(result) {
// invoked with the response object as single argument when operation completed
});
```
--------------------------------
### Removing Files
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Methods for removing single files, multiple files, or clearing all files from the Sass.js file system.
```APIDOC
## Removing Files
### `sass.removeFile(path, callback)`
**Description**: Removes a single file from the Sass.js file system.
**Method**: `sass.removeFile`
**Parameters**:
#### Path Parameter
- **path** (string) - Required - The path of the file to remove.
#### Callback Function
- **callback** (function) - Required - A function that is called after the file removal attempt.
- **success** (boolean) - `true` if the file was successfully removed, `false` otherwise.
### `sass.removeFile(fileList, callback)`
**Description**: Removes multiple files from the Sass.js file system.
**Method**: `sass.removeFile`
**Parameters**:
#### Path Parameter
- **fileList** (array) - Required - An array of file paths to remove.
#### Callback Function
- **callback** (function) - Required - A function that is called after the file removal attempt.
- **result** (object) - An object where keys are file paths and values are booleans indicating success (`true`) or failure (`false`) for each file.
### `sass.clearFiles(callback)`
**Description**: Removes all files from the Sass.js file system.
**Method**: `sass.clearFiles`
**Parameters**:
#### Callback Function
- **callback** (function) - Required - A function that is called when the operation is completed.
### Request Example (Remove Single File)
```javascript
sass.removeFile('path/to/file.scss', function(success) {
console.log('File removed:', success);
});
```
### Request Example (Remove Multiple Files)
```javascript
sass.removeFile(['path1.scss', 'path2.scss'], function(result) {
console.log('Multiple files removed:', result);
});
```
### Request Example (Clear All Files)
```javascript
sass.clearFiles(function() {
console.log('All files cleared.');
});
```
```
--------------------------------
### Build Sass.js in Debug Mode
Source: https://github.com/medialize/sass.js/blob/master/docs/build.md
This command builds Sass.js with Emscripten debug mode enabled. This is crucial for debugging callstacks and identifying issues, particularly when using the Emterpreter for synchronous code execution.
```bash
npm run build:debug
```
--------------------------------
### Pass Data to Sass.js Importer Callback
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Enables passing arbitrary JSON-serializable data to the Importer Callback, accessible via `request.options` within the callback.
```javascript
sass.options({
importer: {},
}, function callback() {
// invoked without arguments when operation completed
});
```
--------------------------------
### Configure Source Maps for Sass.js Compilation
Source: https://context7.com/medialize/sass.js/llms.txt
Shows how to configure Sass.js to generate source maps with custom settings like file names, root paths, and content embedding. This is useful for debugging compiled CSS.
```javascript
var Sass = require('sass.js');
Sass.options({
sourceMapFile: 'output.css.map', // Enables source map generation
sourceMapRoot: '/src/', // Source root in map
inputPath: 'input.scss', // Input path for map
outputPath: 'output.css', // Output path for map
sourceMapContents: true, // Include source contents
sourceMapEmbed: false, // Don't embed as data URI
sourceMapOmitUrl: false // Include sourceMappingURL comment
}, function() {
var scss = '$size: 50px; .element { width: $size; height: $size; }';
Sass.compile(scss, function(result) {
if (result.status === 0) {
console.log(result.text);
console.log('Source map:', JSON.stringify(result.map, null, 2));
// {
// "version": 3,
// "sourceRoot": "/src/",
// "file": "output.css",
// "sources": ["input.scss"],
// "sourcesContent": ["$size: 50px; .element { width: $size; height: $size; }"],
// "mappings": "...",
// "names": []
// }
}
});
});
```
--------------------------------
### Configure Sass.js Source Map Options
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Configures various options for generating source maps during Sass compilation, including file paths, content embedding, and URL handling.
```javascript
sass.options({
// Path to source map file
// Enables the source map generating
// Used to create sourceMappingUrl
sourceMapFile: 'file',
// Pass-through as sourceRoot property
sourceMapRoot: 'root',
// The input path is used for source map generation.
// It can be used to define something with string
// compilation or to overload the input file path.
// It is set to "stdin" for data contexts
// and to the input file on file contexts.
inputPath: 'stdin',
// The output path is used for source map generation.
// Libsass will not write to this file, it is just
// used to create information in source-maps etc.
outputPath: 'stdout',
// Embed included contents in maps
sourceMapContents: true,
// Embed sourceMappingUrl as data uri
sourceMapEmbed: false,
// Disable sourceMappingUrl in css output
sourceMapOmitUrl: true,
}, function callback() {
// invoked without arguments when operation completed
});
```
--------------------------------
### List and Remove Files in Sass.js Virtual Filesystem
Source: https://context7.com/medialize/sass.js/llms.txt
Manages files within Sass.js's virtual filesystem by listing all registered files, removing specific files (individually or in batches), and clearing the entire filesystem. These operations are essential for maintaining the state of the virtual filesystem during a compilation session.
```javascript
var sass = new Sass();
// List all registered files
sass.listFiles(function(files) {
console.log('Registered files:', files);
// ['styles/main.scss', 'styles/_variables.scss']
});
// Remove a single file
sass.removeFile('styles/main.scss', function(success) {
console.log('File removed:', success);
});
// Remove multiple files
sass.removeFile(['file1.scss', 'file2.scss'], function(results) {
console.log(results); // { 'file1.scss': true, 'file2.scss': true }
});
// Clear all files
sass.clearFiles(function() {
console.log('All files removed');
});
```
--------------------------------
### Sass.js File Path Variation Resolution (JavaScript)
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
This snippet shows how Sass.js resolves file names for `@import` statements by providing a list of potential file paths. It includes a utility function `Sass.findPathVariation` that uses `fs.statSync` to find the correct file on the filesystem.
```javascript
[
// (1) filename as given
"hello/world",
// (2) underscore + given
"hello/_world",
// (3) underscore + given + extension
"hello/_world.scss",
"hello/_world.sass",
"hello/_world.css",
// (4) given + extension
"hello/world.scss",
"hello/world.sass",
"hello/world.css"
]
```
```javascript
var fs = require('fs');
var Sass = require('sass.js');
var file = Sass.findPathVariation(fs.statSync, 'hello/world');
```
--------------------------------
### Register Sass File in Emscripten File System
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Registers a Sass file with its content into the emscripten file system, making it available for `@import` statements during compilation. This function accepts a file path and the source code as arguments, followed by a callback indicating success or failure.
```javascript
sass.writeFile(path, source, function callback(success) {
// (boolean) success is
// `true` when the write was OK,
// `false` when it failed
});
```
--------------------------------
### Read Sass File Content from Emscripten File System
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Retrieves the content of a Sass file from the emscripten file system. It takes a file path and returns the file's content via a callback function. If the read operation fails, `undefined` is returned.
```javascript
sass.readFile(path, function callback(content) {
// (string) content is the file's content,
// `undefined` when the read failed
});
```
--------------------------------
### Build Libsass.js in Debug Mode
Source: https://github.com/medialize/sass.js/blob/master/docs/build.md
This command compiles libsass.js specifically in Emscripten debug mode. It's a targeted build for debugging the Emscripten compilation of libsass.
```bash
npm run libsass:debug
```
--------------------------------
### Custom Importer Callback with Sass.js
Source: https://context7.com/medialize/sass.js/llms.txt
Allows interception and customization of how Sass.js resolves and imports files. You can define custom logic to provide file content, redirect imports, or explicitly handle errors. This requires the Sass.js library and its importer functionality.
```javascript
var Sass = require('sass.js');
Sass.importer(function(request, done) {
// request.current: path being imported
// request.previous: file containing the import
// request.resolved: resolved relative path
// request.path: actual filesystem path (null if not found)
if (request.path) {
// File exists, let libsass handle it
done();
} else if (request.current === 'theme') {
// Provide custom content
done({
content: '$theme-color: #9b59b6; .theme { color: $theme-color; }'
});
} else if (request.current === 'redirect') {
// Redirect to different file
done({
path: '/sass/alternative-file.scss'
});
} else if (request.current === 'error') {
// Return an error
done({
error: 'Import failed: file not allowed'
});
} else {
// Let libsass handle it
done();
}
});
Sass.compile('@import "theme";', function(result) {
console.log(result.text); // .theme { color: #9b59b6; }
});
// Unregister importer
Sass.importer(null);
```
--------------------------------
### Compile SCSS/SASS String to CSS
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Compiles a given SCSS or SASS source string into CSS. For SASS syntax, `indentedSyntax` must be set to `true` in the options.
```javascript
sass.compile(source, function callback(result) {
// invoked with the response object as single argument when operation completed
});
```
```javascript
sass.compile(source, options, function callback(result) {
// invoked with the response object as single argument when operation completed
});
```
--------------------------------
### Compile SCSS String to CSS with Sass.js
Source: https://context7.com/medialize/sass.js/llms.txt
Compiles a given SCSS source string into CSS using the default compilation options. It handles the compilation process and returns the resulting CSS or an error message if compilation fails. This is useful for on-the-fly CSS generation.
```javascript
var Sass = require('sass.js');
var scss = '$primary-color: #3498db; $padding: 20px; .container { background-color: $primary-color; padding: $padding; }';
Sass.compile(scss, function(result) {
if (result.status === 0) {
// Success
console.log(result.text);
// Output: .container { background-color: #3498db; padding: 20px; }
console.log(result.map); // Source map object
} else {
// Error
console.error('Compilation failed:', result.message);
console.error('Line:', result.line, 'Column:', result.column);
}
});
```
--------------------------------
### Sass Compilation Response Object Structure
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Illustrates the structure of the response object returned after a successful Sass compilation. It includes status, compiled CSS text, SourceMap data, and a list of files used during compilation.
```javascript
{
"status": 0,
"text": ".some-selector {\n width: 123px; }\n",
"map": {
"version": 3,
"sourceRoot": "root",
"file": "stdout",
"sources": [
"stdin"
],
"sourcesContent": [
"$someVar: 123px; .some-selector { width: $someVar; }"
],
"mappings": "AAAiB,cAAc,CAAC;EAAE,KAAK,EAA7B,KAAK,GAAkB",
"names": []
},
"files": []
}
```
--------------------------------
### Handle Compilation Errors with Sass.js
Source: https://context7.com/medialize/sass.js/llms.txt
Demonstrates how to parse and display detailed information about SCSS compilation errors. The `result` object returned by `Sass.compile` provides properties like `status`, `file`, `line`, `column`, `message`, and `formatted` output for debugging. Requires the Sass.js library.
```javascript
var Sass = require('sass.js');
var invalidScss = '$foo: 123px;\n\n.bar {\n width: $undefined;\n}\n\nbad-token';
Sass.compile(invalidScss, function(result) {
if (result.status !== 0) {
// Error occurred
console.error('Status:', result.status);
console.error('File:', result.file); // stdin
console.error('Line:', result.line); // 7
console.error('Column:', result.column); // 1
console.error('Message:', result.message); // invalid top-level expression
console.error('Formatted output:');
console.error(result.formatted);
// Error: invalid top-level expression
// on line 7 of stdin
// >> bad-token
// ^
}
});
```
--------------------------------
### Read Files from Sass.js Virtual Filesystem
Source: https://context7.com/medialize/sass.js/llms.txt
Reads the content of files from Sass.js's virtual filesystem. It allows retrieving a single file's content or the content of multiple specified files. This is useful for debugging or inspecting files managed within the virtual filesystem.
```javascript
var sass = new Sass();
// Read a single file
sass.readFile('styles/main.scss', function(content) {
if (content) {
console.log('File content:', content);
} else {
console.log('File not found');
}
});
// Read multiple files
sass.readFile(['styles/main.scss', 'styles/_variables.scss'], function(results) {
console.log(results);
// { 'styles/main.scss': '...content...', 'styles/_variables.scss': '...content...' }
});
```
--------------------------------
### Write Files to Sass.js Virtual Filesystem
Source: https://context7.com/medialize/sass.js/llms.txt
Writes SCSS files to Sass.js's internal virtual filesystem, enabling the use of `@import` statements in subsequent compilations. Supports writing single files or multiple files simultaneously. This is crucial for managing project structure and dependencies within the Sass compilation context.
```javascript
var sass = new Sass('dist/sass.worker.js');
// Write a single file
sass.writeFile('variables.scss', '$primary: #e74c3c; $secondary: #2ecc71;', function(success) {
if (success) {
console.log('File written successfully');
}
});
// Write multiple files at once
sass.writeFile({
'styles/main.scss': '@import "variables"; body { color: $primary; }',
'styles/_variables.scss': '$primary: #3498db;',
'styles/components/_button.scss': '.btn { background: $primary; }'
}, function(results) {
console.log(results); // { 'styles/main.scss': true, ... }
});
// Compile using imported files
sass.compile('@import "styles/main";', function(result) {
console.log(result.text);
});
```
--------------------------------
### Compile SASS Syntax with Sass.js
Source: https://context7.com/medialize/sass.js/llms.txt
Compiles SCSS code written in the indented SASS syntax (rather than the brace-and-semicolon syntax). This is achieved by setting the `indentedSyntax` option to `true` within Sass.js options. Requires the Sass.js library.
```javascript
var Sass = require('sass.js');
var sassSource = '$color: #e67e22\n\n.header\n background: $color\n padding: 10px';
Sass.options({
indentedSyntax: true, // Enable SASS syntax
style: Sass.style.expanded
}, function() {
Sass.compile(sassSource, function(result) {
if (result.status === 0) {
console.log(result.text);
// .header {
// background: #e67e22;
// padding: 10px;
// }
}
});
});
```
--------------------------------
### Sass Compilation Error Response Object Structure
Source: https://github.com/medialize/sass.js/blob/master/docs/api.md
Details the structure of the response object when a Sass compilation error occurs. It includes error status, file, line, column, error message, and a human-readable formatted error string.
```javascript
{
"status": 1,
"file": "stdin",
"line": 7,
"column": 1,
"message": "invalid top-level expression",
"formatted": "Error: invalid top-level expression\n on line 7 of stdin\n>> bad-token-test\n ^\n"
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.