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 support for configuring Shared Sass Resources for using global mixins, variables, etc. #300

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions demo/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ function App() {
This text is styled by global configured SASS
</p>
<p className="imported-sass">This text is styled by imported SASS</p>
<p className="imported-sass-shared-var">This text is styled by imported SASS using a shared mixin and variable</p>
<p className="bg-yellow-400 font-bold m-5 text-red-500">
This text is styled by Tailwind CSS
</p>
Expand Down
1 change: 1 addition & 0 deletions demo/assets/_scss/sharedSassResources/color-vars.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
$limeGreen: #32cd32;
5 changes: 5 additions & 0 deletions demo/assets/_scss/sharedSassResources/mixins.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
@mixin desktop {
@media only screen and (min-width: 900px) {
@content;
}
}
8 changes: 8 additions & 0 deletions demo/assets/_scss/style.scss
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,12 @@ header {
.imported-sass {
color: pink;
}

.imported-sass-shared-var {
color: purple;

@include desktop {
color: $limeGreen;
}
}
}
4 changes: 4 additions & 0 deletions demo/setupTests.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ jestPreviewConfigure({
publicFolder: 'demo/public',
autoPreview: true,
sassLoadPaths: ['demo/assets/_scss/loadPathsExample'],
sharedSassResources: [
'demo/assets/_scss/sharedSassResources/color-vars.scss',
'demo/assets/_scss/sharedSassResources/mixins.scss',
],
});

window.matchMedia = (query) => ({
Expand Down
22 changes: 21 additions & 1 deletion src/configure.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import path from 'path';
import fs from 'fs';
import chalk from 'chalk';
import { CACHE_FOLDER, SASS_LOAD_PATHS_CONFIG } from './constants';
import { CACHE_FOLDER, SASS_LOAD_PATHS_CONFIG, SASS_SHARED_RESOURCES_CONCAT } from './constants';
import { createCacheFolderIfNeeded } from './utils';
import { debug } from './preview';

Expand All @@ -13,6 +13,7 @@ interface JestPreviewConfigOptions {
autoPreview?: boolean;
publicFolder?: string;
sassLoadPaths?: string[];
sharedSassResources?: string[];
}

export function jestPreviewConfigure(
Expand All @@ -21,6 +22,7 @@ export function jestPreviewConfigure(
autoPreview = false,
publicFolder,
sassLoadPaths,
sharedSassResources,
}: JestPreviewConfigOptions = {
autoPreview: false,
sassLoadPaths: [],
Expand Down Expand Up @@ -72,6 +74,24 @@ export function jestPreviewConfigure(
},
);
}

if (sharedSassResources && sharedSassResources.length > 0) {
createCacheFolderIfNeeded();

const resourceFileContents = sharedSassResources.map((sassResourceFile) => {
const filenameComment = `// ${sassResourceFile}`;
const fileContents = fs.readFileSync(sassResourceFile, "utf-8");

return `${filenameComment}\n${fileContents}`;
});

const resourceFileContentsConcat = resourceFileContents.join('\n\n');

fs.writeFileSync(
path.join(CACHE_FOLDER, SASS_SHARED_RESOURCES_CONCAT),
resourceFileContentsConcat,
);
}
}

// Omit only, skip, todo, concurrent, each. Couldn't use Omit. Just redeclare for simplicity
Expand Down
4 changes: 3 additions & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
export const CACHE_FOLDER = './node_modules/.cache/jest-preview';
export const CACHE_SUB_FOLDER = '.cache/jest-preview';
export const CACHE_FOLDER = `./node_modules/${CACHE_SUB_FOLDER}`;
export const SASS_LOAD_PATHS_CONFIG = 'cache-sass-load-paths.config';
export const SASS_SHARED_RESOURCES_CONCAT = '_sass-resources-concat.scss';
55 changes: 44 additions & 11 deletions src/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { pathToFileURL } from 'url';
import camelcase from 'camelcase';
import slash from 'slash';
import { transform } from '@svgr/core';
import { CACHE_FOLDER, SASS_LOAD_PATHS_CONFIG } from './constants';
import { CACHE_FOLDER, CACHE_SUB_FOLDER, SASS_LOAD_PATHS_CONFIG, SASS_SHARED_RESOURCES_CONCAT } from './constants';
import { createCacheFolderIfNeeded } from './utils';

// https://github.com/vitejs/vite/blob/c29613013ca1c6d9c77b97e2253ed1f07e40a544/packages/vite/src/node/plugins/css.ts#L97-L98
Expand Down Expand Up @@ -372,6 +372,10 @@ module.exports = ${output.cssModulesExportedTokens || '{}'}`,
};
}

type BuildCssOptions = {
prependUseShared: boolean;
};

function processSass(filename: string): string {
let sass;

Expand All @@ -397,6 +401,20 @@ function processSass(filename: string): string {
sassLoadPathsConfig = [];
}

// Workaround for ?bug? with sass.compileString that the location of the source file is not automatically included in load paths
sassLoadPathsConfig.push(path.parse(filename).dir);

const sharedSassResourcesPath = path.join(CACHE_FOLDER, SASS_SHARED_RESOURCES_CONCAT);
const buildOptions: BuildCssOptions = { prependUseShared: false};

if (fs.existsSync(sharedSassResourcesPath)) {
buildOptions.prependUseShared = true;
Copy link
Collaborator

Choose a reason for hiding this comment

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

@mikeb-meq I think we can move the logic to create sassPrefixedWithSharedResources to be here, the reasons should be:

  • For consistency with sassLoadPathsConfig. We might update the buildCssResult arguments to `buildCssResult(sass: any, sassLoadPathsConfig: string[], sassPrefixedWithSharedResources: string, filename: string)
  • Can remove BuildCssOptions

}

return buildCssResult(sass, sassLoadPathsConfig, filename, buildOptions);
}

function buildCssResult(sass: any, sassLoadPathsConfig: string[], filename: string, options: BuildCssOptions): string {
let cssResult;

// An importer that redirects relative URLs starting with "~" to `node_modules`
Expand All @@ -412,17 +430,32 @@ function processSass(filename: string): string {
);
};

if (sass.compile) {
cssResult = sass.compile(filename, {
loadPaths: sassLoadPathsConfig,
importers: [
{
findFileUrl(url: string) {
return tildeImporter(url);
},
if (options.prependUseShared && !sass.compileString) {
console.warn("WARNING: Config specifies sharedSassResources, but your version of Sass doesn't support it - consider updating to v1.45.0 or higher.")
Copy link
Collaborator

Choose a reason for hiding this comment

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

Should add a semicolon to the end of this line

}

const compileOptions = {
loadPaths: sassLoadPathsConfig,
importers: [
{
findFileUrl(url: string) {
return tildeImporter(url);
},
],
}).css;
},
],
}

if (options.prependUseShared && sass.compileString) {
// Transform the filename for use in "use" statement
const sharedResourcesFilenameForUse = SASS_SHARED_RESOURCES_CONCAT.replace(/^_|\.scss$/g, '');
// Prepend a "use" statement so shared sass resources are accessible from all source files
const useSharedStatement = `@use '~${CACHE_SUB_FOLDER}/${sharedResourcesFilenameForUse}' as *;`;
const sassContent = fs.readFileSync(filename, 'utf8');
const sassPrefixedWithSharedResources = `${useSharedStatement}\n\n${sassContent}`;

cssResult = sass.compileString(sassPrefixedWithSharedResources, compileOptions).css;
} else if (sass.compile) {
cssResult = sass.compile(filename, compileOptions).css;
}
// Because sass.compile is only introduced since sass version 1.45.0
// For older versions, we have to use the legacy API: renderSync
Expand Down
6 changes: 6 additions & 0 deletions website/docs/api/jestPreviewConfigure.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,9 @@ Default: `false`
Automatically preview the UI in the external browser when the test fails. You don't need to invoke `preview.debug()` by yourself anymore.

Set to `false` if you experience any error or just want to opt out.

## sharedSassResources: string[]

Default: `undefined`
Copy link
Collaborator

Choose a reason for hiding this comment

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

The default value should be [], just for consistency with sassLoadPaths, and no need to check that sharedSassResources is existed. Also, I think we can move this doc right below the sassLoadPaths doc, so we wrap all the sass configs in the same area.


Optional list of paths to SASS files that define shared resources (e.g. variables, mixins, etc). The paths are relative to the root of the project. Requires SASS v1.45.0 or higher.