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 3 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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

## 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
- BREAKING: Drop support for node < 18
- INTERNAL: Remove `sass` as a peer-dependency.
- INTERNAL: Update dependencies

## 7.0.1 (01/04/24)
Expand Down
60 changes: 46 additions & 14 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,8 +217,9 @@ 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
Expand All @@ -218,15 +234,31 @@ 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)
and passing it into the configuration for `runSass`:
If you use the Dart Sass [Node.js package importer][pkg-importer] (e.g. `@use
'pkg:accoutrement'`), you'll need to include `NodePackageImporter` in the
options passed to `runSass`:
jgerigmeyer marked this conversation as resolved.
Show resolved Hide resolved

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

const sassFile = path.join(__dirname, 'test.scss');
sassTrue.runSass({ describe, it }, sassFile, {
importers: [new NodePackageImporter()],
});
```

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('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
45 changes: 35 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,7 +69,7 @@ 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);
Expand All @@ -80,15 +80,40 @@ export const runSass = function (
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',
);
}

const compiler = trueOpts.sourceType === 'string' ? compileString : compile;
const parsedCss = compiler(src, sassOpts).css;
// 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.',
);
}

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.`);
}
}

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
95 changes: 94 additions & 1 deletion test/main.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable global-require */

const path = require('path');
const path = require('node:path');

const { expect } = require('chai');
const { diffStringsUnified } = require('jest-diff');
Expand Down Expand Up @@ -33,6 +33,35 @@ describe('#fail', () => {
});

describe('#runSass', () => {
it('throws if `style: "compressed"` is used', () => {
const sass = [
'@use "true" as *;',
'@include test-module("Module") {',
' @include test("Test") {',
' @include assert("Assertion") {',
' @include output() {',
' height: 10px;',
' }',
' @include expect() {',
' height: 10px;',
' }',
' }',
' }',
'}',
].join('\n');
const mock = function (name, cb) {
cb();
};
const attempt = function () {
sassTrue.runSass({ describe: mock, it: mock }, sass, {
style: 'compressed',
});
};
expect(attempt).to.throw(
'requires the default Sass `expanded` output style',
);
});

it('throws if arguments do not match newer API', () => {
const sass = [
'@use "true" as *;',
Expand Down Expand Up @@ -114,6 +143,70 @@ describe('#runSass', () => {
};
expect(attempt).not.to.throw();
});

it('can specify sass implementation to use [string]', () => {
const sass = [
'@use "true" as *;',
'@include test-module("Module") {',
' @include test("Test") {',
' @include assert("Assertion") {',
' @include output() {',
' -property: value;',
' }',
' @include expect() {',
' -property: value;',
' }',
' }',
' }',
'}',
].join('\n');
const mock = function (name, cb) {
cb();
};
const attempt = function () {
sassTrue.runSass(
{
describe: mock,
it: mock,
sourceType: 'string',
sass: 'sass-embedded',
},
sass,
);
};
expect(attempt).not.to.throw();
});

it('can specify sass implementation to use [object]', () => {
const mock = function (name, cb) {
cb();
};
const attempt = function () {
sassTrue.runSass(
{
describe: mock,
it: mock,
sass: {
compile() {
throw new Error('Custom sass implementation called');
},
},
},
'',
);
};
expect(attempt).to.throw('Custom sass implementation called');
});

it('throws if sass implementation is not found', () => {
const mock = function (name, cb) {
cb();
};
const attempt = function () {
sassTrue.runSass({ describe: mock, it: mock, sass: 'foobar' }, '');
};
expect(attempt).to.throw('Cannot find Dart Sass (`foobar`) dependency.');
});
});

describe('#parse', () => {
Expand Down
2 changes: 1 addition & 1 deletion test/sass.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable global-require */

const path = require('path');
const path = require('node:path');

const sassFile = path.join(__dirname, 'scss', 'test.scss');
let runSass;
Expand Down
Loading