Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option to specify sass implementation to use. #274

Merged
merged 5 commits into from
Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,15 @@

## 8.0.0-beta.0 (unreleased)

- FEATURE: Add True `sass` option (`string` or Sass implementation instance,
defaults to `'sass'`) to allow using either `sass` or `embedded-sass`.
jgerigmeyer marked this conversation as resolved.
Show resolved Hide resolved
- FEATURE: Add the
[Node.js package importer](https://sass-lang.com/documentation/js-api/classes/nodepackageimporter/)
to the Sass `importers` option by default, if Dart Sass v1.71 or later is
available. Users can opt out by providing their own `importers` option, e.g.
`{ importers: [] }`.
- BREAKING: Drop support for node < 18
- INTERNAL: Remove `sass` as a peer-dependency.
- INTERNAL: Update dependencies

## 7.0.1 (01/04/24)
Expand Down
57 changes: 40 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,26 @@ Import in your test directory,
like any other Sass file:

```scss
@use 'true' as *;
@use 'pkg:sass-true' as *;
```

Depending on your setup,
you may need to include the full path name:
If you are not using the Sass [Node.js package importer][pkg-importer], you may
need to include the full path name:

```scss
// This is only an example, your path may be different
@use '../node_modules/sass-true' as *;
```

Or if you are using the [JavaScript test runner integration][js-runner]:

```scss
@use 'true' as *;
```

[pkg-importer]: https://sass-lang.com/documentation/js-api/classes/nodepackageimporter/
[js-runner]: #using-mocha-jest-or-other-js-test-runners

## One Setting

`$terminal-output` (boolean),
Expand Down Expand Up @@ -146,7 +155,8 @@ when upgrading from an older version of True.
npm install --save-dev sass-true
```

2. [Optional] Install `sass` (Dart Sass), if not already installed.
2. [Optional] Install Dart Sass (`sass` or `sass-embedded`), if not already
installed.

```bash
npm install --save-dev sass
Expand All @@ -157,7 +167,7 @@ when upgrading from an older version of True.
4. Write a shim JS test file in `test/sass.test.js`:

```js
const path = require('path');
const path = require('node:path');
const sassTrue = require('sass-true');

const sassFile = path.join(__dirname, 'test.scss');
Expand Down Expand Up @@ -185,12 +195,17 @@ You can call `runSass` more than once, if you have multiple Sass test files you
want to run separately.

The first argument is an object with required `describe` and `it` options, and
optional `contextLines` and `sourceType` options.
optional `sass`, `contextLines` and `sourceType` options.

Any JS test runner with equivalents to Mocha's or Jest's `describe` and `it`
should be usable in the same way: just pass your test runner's `describe` and
`it` equivalents in the first argument to `runSass`.

The `sass` option is an optional string name of a Dart Sass implementation
installed in the current environment (e.g. `'embedded-sass'` or `'sass'`), or a
Dart Sass implementation instance itself. If none is provided, this defaults to
`'sass'`.

If True can't parse the CSS output, it'll give you some context lines of CSS as
part of the error message. This context will likely be helpful in understanding
the parse failure. By default it provides up to 10 lines of context; if you need
Expand All @@ -202,14 +217,22 @@ file (passed through to Sass'
[`compile`](https://sass-lang.com/documentation/js-api/modules#compile)
function), or a string of source Sass (passed through to Sass'
[`compileString`](https://sass-lang.com/documentation/js-api/modules#compileString)
function). By default it is expected to be a path, and `sass.compile` is used --
to pass in a source string (and use `sass.compileString`), add `sourceType: 'string'` to your options passed in as the first argument to `runSass`.
function). By default it is expected to be a path, and `sass.compile` is used.
To pass in a source string (and use `sass.compileString`), add `sourceType:
'string'` to your options passed in as the first argument to `runSass`.

The third (optional) argument to `runSass` accepts the [same
options](https://sass-lang.com/documentation/js-api/interfaces/Options) that
Sass' `compile` or `compileString` expect, and these are passed directly through
to Sass. The only modification `runSass` makes is to add True's sass path to the
`loadPaths` option, so `@use 'true';` works in your Sass test file.
Sass' `compile` or `compileString` expect (e.g. `importers`, `loadPaths`, or
`style`), and these are passed directly through to Sass.

By default, True makes two modifications to these options. First, True's sass
path is added to the `loadPaths` option, so `@use 'true';` works in your Sass
test file. Second, if Dart Sass v1.71 or greater is installed, `importers` is
set to an array containing the [Node.js package importer][pkg-importer], which
supports `pkg:` imports to resolve `@use` and `@import` for external modules
installed via npm or Yarn. If `importers` is set (even as an empty array
`importers: []`), it will override this default importer.

**Note:** True requires the
[default Sass `'expanded'` output style](https://sass-lang.com/documentation/js-api/modules#OutputStyle),
Expand All @@ -218,15 +241,15 @@ and will not work if `{ style: 'compressed' }` is used in the third argument to

### Custom Importers

If you use Webpack's tilde notation, like `@use '~accoutrement/sass/tools'`,
you'll need to tell `runSass` how to handle that. That will require writing a
[custom importer](https://sass-lang.com/documentation/js-api/interfaces/FileImporter)
If you use tilde notation (e.g. `@use '~accoutrement/sass/tools'`) or another
method for importing Sass files from `node_modules`, you'll need to tell
`runSass` how to handle that. That will require writing a [custom
importer](https://sass-lang.com/documentation/js-api/interfaces/FileImporter)
and passing it into the configuration for `runSass`:

```js
const path = require('path');
const { pathToFileURL } = require('url');

const path = require('node:path');
const { pathToFileURL } = require('node:url');
const sassTrue = require('sass-true');

const importers = [
Expand Down
13 changes: 8 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
"eyeglass-module"
],
"homepage": "https://www.oddbird.net/true/",
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"license": "BSD-3-Clause",
"repository": {
"type": "git",
Expand Down Expand Up @@ -63,9 +61,6 @@
"release": "run-s commit docs",
"prepack": "yarn run release"
},
"peerDependencies": {
"sass": ">=1.45.0"
},
"dependencies": {
"@adobe/css-tools": "^4.3.3",
"jest-diff": "^29.7.0",
Expand All @@ -92,12 +87,20 @@
"postcss": "^8.4.35",
"prettier": "^3.2.5",
"sass": "^1.71.1",
"sass-embedded": "^1.71.1",
"sassdoc": "^2.7.4",
"sassdoc-theme-herman": "^5.0.1",
"stylelint": "^16.2.1",
"stylelint-config-standard-scss": "^13.0.0",
"typescript": "^5.3.3"
},
"main": "./lib/index.js",
"types": "./lib/index.d.ts",
"exports": {
"types": "./lib/index.d.ts",
"sass": "./_index.scss",
"default": "./lib/index.js"
},
"eyeglass": {
"needs": "*",
"name": "true",
Expand Down
56 changes: 46 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable no-use-before-define */
/* eslint-disable @typescript-eslint/no-use-before-define */

import assert from 'node:assert';
import path from 'node:path';

import {
CssAtRuleAST,
Expand All @@ -9,12 +12,8 @@ import {
parse as cssParse,
stringify as cssStringify,
} from '@adobe/css-tools';
import * as assert from 'assert';
import { diffStringsUnified } from 'jest-diff';
import { find, forEach, last, startsWith } from 'lodash';
import * as path from 'path';
import type { Options, StringOptions } from 'sass';
import { compile, compileString } from 'sass';

import * as constants from './constants';
import {
Expand All @@ -28,6 +27,7 @@ import {
export interface TrueOptions {
describe: (description: string, fn: () => void) => void;
it: (description: string, fn: () => void) => void;
sass?: any;
sourceType?: 'path' | 'string';
contextLines?: number;
}
Expand Down Expand Up @@ -69,26 +69,62 @@ export type Parser = (rule: Rule, ctx: Context) => Parser;
export const runSass = function (
trueOptions: TrueOptions,
src: string,
sassOptions?: Options<'sync'> | StringOptions<'sync'>,
sassOptions?: any,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is unfortunate, but unavoidable if we really want to support any Sass implementation.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't tried it, but could you do something like Options<'sync'> | StringOptions<'sync'> | any? Not sure if that just removes any benefit anyways, though.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If these weren't TypeScript types, that would work. But the problem is until runtime we don't know whether sass or sass-embedded (or some other future implementation?) is available, so we don't have a place we can safely import the Options and StringOptions types from.

) {
const trueOpts = Object.assign({}, trueOptions);
const sassOpts = Object.assign({}, sassOptions);

// Add True's sass to `loadPaths`
const sassPath = path.join(__dirname, '..', 'sass');
if (sassOpts.loadPaths) {
sassOpts.loadPaths.push(sassPath);
} else {
sassOpts.loadPaths = [sassPath];
jgerigmeyer marked this conversation as resolved.
Show resolved Hide resolved
}

// Warn if arguments match v6 API
// Error if arguments match v6 API
if (typeof src !== 'string' || !trueOptions.describe || !trueOptions.it) {
throw new Error(
'The arguments provided to `runSass` do not match the new API introduced in True v7. Refer to the v7 release notes for migration documentation: https://github.com/oddbird/true/releases/tag/v7.0.0',
'The arguments provided to `runSass` do not match the new API ' +
'introduced in True v7. Refer to the v7 release notes ' +
'for migration documentation: ' +
'https://github.com/oddbird/true/releases/tag/v7.0.0',
);
}

// Error if `style: "compressed"` is used
if (sassOpts.style === 'compressed') {
throw new Error(
'True requires the default Sass `expanded` output style, ' +
'but `style: "compressed"` was used.',
);
}

const compiler = trueOpts.sourceType === 'string' ? compileString : compile;
const parsedCss = compiler(src, sassOpts).css;
let compiler;
if (trueOpts.sass && typeof trueOpts.sass !== 'string') {
compiler = trueOpts.sass;
} else {
const sassPkg = trueOpts.sass ?? 'sass';
try {
// eslint-disable-next-line global-require
compiler = require(sassPkg);
} catch (err) {
throw new Error(`Cannot find Dart Sass (\`${sassPkg}\`) dependency.`);
}
}

// Add the Sass Node.js package importer, if available
if (!sassOpts.importers) {
try {
jgerigmeyer marked this conversation as resolved.
Show resolved Hide resolved
sassOpts.importers = [new compiler.NodePackageImporter()];
} catch (err) {
// skip if `NodePackageImporter` isn't available
}
}

const compilerFn =
trueOpts.sourceType === 'string' ? 'compileString' : 'compile';
const parsedCss = compiler[compilerFn](src, sassOpts).css;
const modules = parse(parsedCss, trueOpts.contextLines);

forEach(modules, (module) => {
Expand Down
Loading