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 all 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
2 changes: 1 addition & 1 deletion demo/__tests__/transform.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ describe('transform', () => {
render(<App />);
// TODO: To refactor this test. It frequently need to be updated.
expect(document.body.outerHTML).toMatchInlineSnapshot(
`"<body><div><div class=\\"App\\"><header class=\\"App-header\\"><div class=\\"sc-gsnTZi kykGJG\\"><img src=\\"/logo.svg\\" class=\\"App-logo\\" alt=\\"logo\\" height=\\"100\\"><svg xmlns=\\"http://www.w3.org/2000/svg\\" width=\\"410\\" height=\\"100\\" fill=\\"none\\" viewBox=\\"0 0 410 404\\"><path fill=\\"url(#paint0_linear)\\" d=\\"M399.641 59.5246L215.643 388.545C211.844 395.338 202.084 395.378 198.228 388.618L10.5817 59.5563C6.38087 52.1896 12.6802 43.2665 21.0281 44.7586L205.223 77.6824C206.398 77.8924 207.601 77.8904 208.776 77.6763L389.119 44.8058C397.439 43.2894 403.768 52.1434 399.641 59.5246Z\\"></path><path fill=\\"url(#paint1_linear)\\" d=\\"M292.965 1.5744L156.801 28.2552C154.563 28.6937 152.906 30.5903 152.771 32.8664L144.395 174.33C144.198 177.662 147.258 180.248 150.51 179.498L188.42 170.749C191.967 169.931 195.172 173.055 194.443 176.622L183.18 231.775C182.422 235.487 185.907 238.661 189.532 237.56L212.947 230.446C216.577 229.344 220.065 232.527 219.297 236.242L201.398 322.875C200.278 328.294 207.486 331.249 210.492 326.603L212.5 323.5L323.454 102.072C325.312 98.3645 322.108 94.137 318.036 94.9228L279.014 102.454C275.347 103.161 272.227 99.746 273.262 96.1583L298.731 7.86689C299.767 4.27314 296.636 0.855181 292.965 1.5744Z\\"></path><defs><linearGradient id=\\"paint0_linear\\" x1=\\"6\\" x2=\\"235\\" y1=\\"33\\" y2=\\"344\\" gradientUnits=\\"userSpaceOnUse\\"><stop stop-color=\\"#41D1FF\\"></stop><stop offset=\\"1\\" stop-color=\\"#BD34FE\\"></stop></linearGradient><linearGradient id=\\"paint1_linear\\" x1=\\"194.651\\" x2=\\"236.076\\" y1=\\"8.818\\" y2=\\"292.989\\" gradientUnits=\\"userSpaceOnUse\\"><stop stop-color=\\"#FFEA83\\"></stop><stop offset=\\"0.083\\" stop-color=\\"#FFDD35\\"></stop><stop offset=\\"1\\" stop-color=\\"#FFA800\\"></stop></linearGradient></defs></svg></div><img src=\\"/demo/assets/images/logo.svg\\" class=\\"logo2\\" alt=\\"logo2\\"><p>Hello Vite + React!</p><p class=\\"less-p\\">Less: Blue + Dynamic size (break point 400px)</p><p class=\\"less-child-p\\">Less: Yellow</p><p class=\\"_scssModule_ujx1w_1\\">Styled by SCSS Modules</p><p class=\\"sc-bczRLJ dgihId\\">This text is styled by styled-components</p><p class=\\"global-css\\">This text is styled by global css which is not imported to App.tsx</p><p class=\\"_cssModule_1a0qn_1\\">This text is styled by CSS Modules</p><p class=\\"global-configured-sass\\">This text is styled by global configured SASS</p><p class=\\"imported-sass\\">This text is styled by imported SASS</p><p class=\\"bg-yellow-400 font-bold m-5 text-red-500\\">This text is styled by Tailwind CSS</p><button class=\\"css-1b07vmx-App\\">Hover to change color.</button><p class=\\"css-2m18qq\\">Styled by Emotion</p><p class=\\"c-gqdJwI\\">Styled by Stiches</p><p class=\\"load-path-sass\\">This text is styled by SASS from load paths</p><p class=\\"animate__animated animate__bounce\\">An animated element style using @use ~</p><div class=\\"animated fadeIn\\"><p>An animated element style using import ~</p><p>Watch me fade in!</p></div><p><button data-testid=\\"increase\\" type=\\"button\\">count is: <div data-testid=\\"count\\">0</div></button></p><p>Edit <code>App.tsx</code> and save to test HMR updates.</p><p><a class=\\"App-link\\" href=\\"https://reactjs.org\\" target=\\"_blank\\" rel=\\"noopener noreferrer\\">Learn React</a> | <a class=\\"App-link\\" href=\\"https://vitejs.dev/guide/features.html\\" target=\\"_blank\\" rel=\\"noopener noreferrer\\">Vite Docs</a></p></header></div></div></body>"`,
`"<body><div><div class=\\"App\\"><header class=\\"App-header\\"><div class=\\"sc-gsnTZi kykGJG\\"><img src=\\"/logo.svg\\" class=\\"App-logo\\" alt=\\"logo\\" height=\\"100\\"><svg xmlns=\\"http://www.w3.org/2000/svg\\" width=\\"410\\" height=\\"100\\" fill=\\"none\\" viewBox=\\"0 0 410 404\\"><path fill=\\"url(#paint0_linear)\\" d=\\"M399.641 59.5246L215.643 388.545C211.844 395.338 202.084 395.378 198.228 388.618L10.5817 59.5563C6.38087 52.1896 12.6802 43.2665 21.0281 44.7586L205.223 77.6824C206.398 77.8924 207.601 77.8904 208.776 77.6763L389.119 44.8058C397.439 43.2894 403.768 52.1434 399.641 59.5246Z\\"></path><path fill=\\"url(#paint1_linear)\\" d=\\"M292.965 1.5744L156.801 28.2552C154.563 28.6937 152.906 30.5903 152.771 32.8664L144.395 174.33C144.198 177.662 147.258 180.248 150.51 179.498L188.42 170.749C191.967 169.931 195.172 173.055 194.443 176.622L183.18 231.775C182.422 235.487 185.907 238.661 189.532 237.56L212.947 230.446C216.577 229.344 220.065 232.527 219.297 236.242L201.398 322.875C200.278 328.294 207.486 331.249 210.492 326.603L212.5 323.5L323.454 102.072C325.312 98.3645 322.108 94.137 318.036 94.9228L279.014 102.454C275.347 103.161 272.227 99.746 273.262 96.1583L298.731 7.86689C299.767 4.27314 296.636 0.855181 292.965 1.5744Z\\"></path><defs><linearGradient id=\\"paint0_linear\\" x1=\\"6\\" x2=\\"235\\" y1=\\"33\\" y2=\\"344\\" gradientUnits=\\"userSpaceOnUse\\"><stop stop-color=\\"#41D1FF\\"></stop><stop offset=\\"1\\" stop-color=\\"#BD34FE\\"></stop></linearGradient><linearGradient id=\\"paint1_linear\\" x1=\\"194.651\\" x2=\\"236.076\\" y1=\\"8.818\\" y2=\\"292.989\\" gradientUnits=\\"userSpaceOnUse\\"><stop stop-color=\\"#FFEA83\\"></stop><stop offset=\\"0.083\\" stop-color=\\"#FFDD35\\"></stop><stop offset=\\"1\\" stop-color=\\"#FFA800\\"></stop></linearGradient></defs></svg></div><img src=\\"/demo/assets/images/logo.svg\\" class=\\"logo2\\" alt=\\"logo2\\"><p>Hello Vite + React!</p><p class=\\"less-p\\">Less: Blue + Dynamic size (break point 400px)</p><p class=\\"less-child-p\\">Less: Yellow</p><p class=\\"_scssModule_ujx1w_1\\">Styled by SCSS Modules</p><p class=\\"sc-bczRLJ dgihId\\">This text is styled by styled-components</p><p class=\\"global-css\\">This text is styled by global css which is not imported to App.tsx</p><p class=\\"_cssModule_1a0qn_1\\">This text is styled by CSS Modules</p><p class=\\"global-configured-sass\\">This text is styled by global configured SASS</p><p class=\\"imported-sass\\">This text is styled by imported SASS</p><p class=\\"imported-sass-shared-var\\">This text is styled by imported SASS using a shared mixin and variable</p><p class=\\"bg-yellow-400 font-bold m-5 text-red-500\\">This text is styled by Tailwind CSS</p><button class=\\"css-1b07vmx-App\\">Hover to change color.</button><p class=\\"css-2m18qq\\">Styled by Emotion</p><p class=\\"c-gqdJwI\\">Styled by Stiches</p><p class=\\"load-path-sass\\">This text is styled by SASS from load paths</p><p class=\\"animate__animated animate__bounce\\">An animated element style using @use ~</p><div class=\\"animated fadeIn\\"><p>An animated element style using import ~</p><p>Watch me fade in!</p></div><p><button data-testid=\\"increase\\" type=\\"button\\">count is: <div data-testid=\\"count\\">0</div></button></p><p>Edit <code>App.tsx</code> and save to test HMR updates.</p><p><a class=\\"App-link\\" href=\\"https://reactjs.org\\" target=\\"_blank\\" rel=\\"noopener noreferrer\\">Learn React</a> | <a class=\\"App-link\\" href=\\"https://vitejs.dev/guide/features.html\\" target=\\"_blank\\" rel=\\"noopener noreferrer\\">Vite Docs</a></p></header></div></div></body>"`,
);
});
});
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
4 changes: 3 additions & 1 deletion examples/angular/src/app/app.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ styleUrls.forEach((styleUrl) => import(styleUrl));
describe('App', () => {
it('should work as expected', async () => {
const user = userEvent.setup();
await render(AppComponent);
const { detectChanges } = await render(AppComponent);

await user.click(screen.getByTestId('increase'));
await user.click(screen.getByTestId('increase'));
Expand All @@ -16,6 +16,8 @@ describe('App', () => {
await user.click(screen.getByTestId('increase'));
await user.click(screen.getByTestId('increase'));

detectChanges();

// Open http://localhost:3336 to see preview
// Require to run `jest-preview` server before
preview.debug();
Expand Down
8 changes: 5 additions & 3 deletions examples/angular/src/app/counter/counter.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { render, screen } from '@testing-library/angular';
import userEvent from '@testing-library/user-event';
// import preview from 'jest-preview';
import preview from 'jest-preview';
import { CounterComponent } from './counter.component';
import './counter.component.css';

describe(CounterComponent.name, () => {
it('should work as expected', async () => {
const user = userEvent.setup();
await render(CounterComponent);
const { detectChanges } = await render(CounterComponent);

await user.click(screen.getByTestId('increase'));
await user.click(screen.getByTestId('increase'));
Expand All @@ -16,9 +16,11 @@ describe(CounterComponent.name, () => {
await user.click(screen.getByTestId('increase'));
await user.click(screen.getByTestId('increase'));

detectChanges();

// Open http://localhost:3336 to see preview
// Require to run `jest-preview` server before
// preview.debug();
preview.debug();

expect(screen.getByTestId('count')).toContainHTML('6');
});
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';
49 changes: 38 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 @@ -397,6 +397,25 @@ 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);

let sassPrefixedWithSharedResources = '';
if (fs.existsSync(sharedSassResourcesPath)) {
// 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');
sassPrefixedWithSharedResources = `${useSharedStatement}\n\n${sassContent}`;
}

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

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

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

if (sass.compile) {
cssResult = sass.compile(filename, {
loadPaths: sassLoadPathsConfig,
importers: [
{
findFileUrl(url: string) {
return tildeImporter(url);
},
if (sassPrefixedWithSharedResources && !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.");
}

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

if (sassPrefixedWithSharedResources && sass.compileString) {
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 @@ -36,6 +36,12 @@ jestPreviewConfigure({
});
```

## sharedSassResources: string[]

Default: `undefined`

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.

## publicFolder: string

Default: `undefined`.
Expand Down
Loading