npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

node-sass-js-importer

v6.0.0

Published

Allows importing CommonJS modules in Sass files parsed by node-sass.

Downloads

109

Readme

node-sass-js-importer

Tests Version on npm

Run JavaScript and import the result as variables into Sass

Motivation

Sharing configuration and other data between all technologies of your stack (and thus, also with Sass) can prove to be a hassle. While basic use cases are coverable through JSON files (see node-sass-json-importer), doing further processing of such data directly in Sass often is suboptimal. Node.js scripts can be the more convenient choice for these kinds of tasks.

This package aims to solve this problem by making the @import/@use rules in Sass work with JavaScript files through custom importers for the current as well as the legacy Sass JavaScript API.

Usage in SCSS Code

Given the following colors.mjs file:

export default {
  primary: 'blue',
  secondary: 'red',
}

The importer allows your Sass file in the same folder to do this:

@import 'colors.mjs';

.some-class {
  background: $primary;
}

Note that @import is somewhat deprecated and you should use @use instead:

@use 'colors.mjs';

.some-class {
  // Data is automatically namespaced:
  background: colors.$primary;
}

To achieve the same behavior as with @import, you can change the namespace to *:

@use 'colors.mjs' as *;

.some-class {
  // Colors are no longer namespaced:
  background: $primary;
}

Importing Strings

As JavaScript values don't map directly to Sass's data types, a common source of confusion is how to handle strings. While Sass allows strings to be both quoted and unqouted, strings containing spaces, commas and/or other special characters have to be wrapped in quotes.

The importer will automatically add quotes around all strings that are not valid unquoted strings or hex colors (and that are not already quoted, of course):

Input | Output | Explanation -|-|- { color: 'red' } | $color: red; | Valid unquoted string { color: '#f00' } | $color: #f00; | Valid hex color { color: "'red'" } | $color: "red"; | Explicitly quoted string { color: "really red" } | $color: "really red"; | Invalid (multi-word) unquoted string

Map Keys

Map keys are always quoted by the importer:

// colors.mjs
export default {
  colors: {
    red: '#f00',
  },
}
@use 'colors.mjs' as *;

:root {
  // This does not work:
  color: map-get($colors, red);

  // Do this instead:
  color: map-get($colors, 'red');
}

Module Formats

The importer supports both CommonJS and ES modules through explicit file extensions (.cjs, .mjs). If you're using a .js extension, the importer will use the same default as the node runtime does (i.e. depending on your package.json's module field).

Resolving Paths

The importer tries to stick to the same path resolution logic as Sass itself. This means that it tries to interpret import requests as (relative) file system paths:

// In /path/to/some-file.scss
@use 'config/colors.mjs'; // Resolves to /path/to/config/colors.mjs

If no according file can be found, further resolving depends on the kind of importer you're using:

Setting up the Importer

[!NOTE]

Some notes on the code samples below:

  1. The examples make use of ES modules, but the importer will work in CommonJS environments just fine.
  2. Examples are using the sass package. However, the same code should work equally well with sass-embedded. The legacy API examples should even work with node-sass (although this is no longer tested since Node Sass has been deprecated).

Sass with Modern JavaScript API

import * as sass from 'sass'
import { jsImporter } from 'node-sass-js-importer'

sass.compile('some-file.scss', {
  importers: [jsImporter],
})

Sass with Legacy JavaScript API

import * as sass from 'sass'
import { legacyJsImporter } from 'node-sass-js-importer'

sass.renderSync({
  file: 'some-file.scss',
  importer: [legacyJsImporter],
})

sass-loader (for webpack/rspack)

This package exposes the createSassLoaderJsImporter/createSassLoaderLegacyJsImporter factory functions to create importers that work well with sass-loader.

While you could just use the importers directly (as documented in the previous section), the sass-loader-specific factory functions enable you to use webpack's request resolution (like pointing to npm packages or aliases) to reference your JavaScript files. Learn more about this in the Resolving Paths section.

To use the importer factory with sass-loader, you need to pass a function to its sassOptions option to get access to the loaderContext object. This object then needs to be passed to the importer factory:

// webpack.config.js / rspack.config.js

import { createSassLoaderJsImporter } from 'node-sass-js-importer'

export default {
  // ...
  {
    loader: 'sass-loader',
    options: {
      sassOptions: loaderContext => ({
        return {
          importers: [
            createSassLoaderJsImporter(loaderContext)
          ],
        }
      },
    },
  },
  // ...
}

[!NOTE]

While the code above uses the importer for the modern Sass JavaScript API, you can also create a legacy importer through the createSassLoaderLegacyJsImporter factory instead. In that case, make sure to also adjust the api option accordingly, if needed.

Credit

The initial implementation of this importer was based on the node-sass-json-importer package.