Skip to content

feat(@angular-devkit/build-angular): enhance Sass rebasing importer for resources URL defined in variables and handling of external paths #27456

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

Merged
merged 1 commit into from
Apr 12, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/

import { buildApplication } from '../../index';
import { OutputHashing } from '../../schema';
import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup';

describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => {
Expand Down Expand Up @@ -164,46 +165,131 @@ describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => {
);
});

it('should not rebase a URL with a namespaced Sass variable reference', async () => {
await harness.writeFile(
'src/styles.scss',
`
@import "a";
`,
);
await harness.writeFile(
'src/a.scss',
`
@use './b' as named;
.a {
background-image: url(named.$my-var)
}
`,
);
await harness.writeFile(
'src/b.scss',
`
@forward './c.scss' show $my-var;
`,
);
await harness.writeFile(
'src/c.scss',
`
$my-var: "https://example.com/example.png";
`,
);
it('should not rebase a URL with a namespaced Sass variable reference that points to an absolute asset', async () => {
await harness.writeFiles({
'src/styles.scss': `@use 'theme/a';`,
'src/theme/a.scss': `
@use './b' as named;
.a {
background-image: url(named.$my-var)
}
`,
'src/theme/b.scss': `@forward './c.scss' show $my-var;`,
'src/theme/c.scss': `$my-var: "https://example.com/example.png";`,
});

harness.useTarget('build', {
...BASE_OPTIONS,
styles: ['src/styles.scss'],
});

const { result } = await harness.executeOnce();
expect(result?.success).toBe(true);
expect(result?.success).toBeTrue();

harness
.expectFile('dist/browser/styles.css')
.content.toContain('url(https://example.com/example.png)');
});

it('should not rebase a URL with a Sass variable reference that points to an absolute asset', async () => {
await harness.writeFiles({
'src/styles.scss': `@use 'theme/a';`,
'src/theme/a.scss': `
@import './b';
.a {
background-image: url($my-var)
}
`,
'src/theme/b.scss': `$my-var: "https://example.com/example.png";`,
});

harness.useTarget('build', {
...BASE_OPTIONS,
styles: ['src/styles.scss'],
});

const { result } = await harness.executeOnce();
expect(result?.success).toBeTrue();

harness
.expectFile('dist/browser/styles.css')
.content.toContain('url(https://example.com/example.png)');
});

it('should rebase a URL with a namespaced Sass variable referencing a local resource', async () => {
await harness.writeFiles({
'src/styles.scss': `@use 'theme/a';`,
'src/theme/a.scss': `
@use './b' as named;
.a {
background-image: url(named.$my-var)
}
`,
'src/theme/b.scss': `@forward './c.scss' show $my-var;`,
'src/theme/c.scss': `$my-var: "./images/logo.svg";`,
'src/theme/images/logo.svg': `<svg></svg>`,
});

harness.useTarget('build', {
...BASE_OPTIONS,
outputHashing: OutputHashing.None,
styles: ['src/styles.scss'],
});

const { result } = await harness.executeOnce();
expect(result?.success).toBeTrue();

harness.expectFile('dist/browser/styles.css').content.toContain(`url("./media/logo.svg")`);
harness.expectFile('dist/browser/media/logo.svg').toExist();
});

it('should rebase a URL with a Sass variable referencing a local resource', async () => {
await harness.writeFiles({
'src/styles.scss': `@use 'theme/a';`,
'src/theme/a.scss': `
@import './b';
.a {
background-image: url($my-var)
}
`,
'src/theme/b.scss': `$my-var: "./images/logo.svg";`,
'src/theme/images/logo.svg': `<svg></svg>`,
});

harness.useTarget('build', {
...BASE_OPTIONS,
outputHashing: OutputHashing.None,
styles: ['src/styles.scss'],
});

const { result } = await harness.executeOnce();
expect(result?.success).toBeTrue();

harness.expectFile('dist/browser/styles.css').content.toContain(`url("./media/logo.svg")`);
harness.expectFile('dist/browser/media/logo.svg').toExist();
});

it('should not process a URL that has been marked as external', async () => {
await harness.writeFiles({
'src/styles.scss': `@use 'theme/a';`,
'src/theme/a.scss': `
.a {
background-image: url("assets/logo.svg")
}
`,
});

harness.useTarget('build', {
...BASE_OPTIONS,
outputHashing: OutputHashing.None,
externalDependencies: ['assets/*'],
styles: ['src/styles.scss'],
});

const { result } = await harness.executeOnce();
expect(result?.success).toBeTrue();

harness.expectFile('dist/browser/styles.css').content.toContain(`url(assets/logo.svg)`);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -32,42 +32,51 @@ export function createCssResourcePlugin(cache?: LoadResultCache): Plugin {
name: 'angular-css-resource',
setup(build: PluginBuild): void {
build.onResolve({ filter: /.*/ }, async (args) => {
const { importer, path, kind, resolveDir, namespace, pluginData = {} } = args;

// Only attempt to resolve url tokens which only exist inside CSS.
// Also, skip this plugin if already attempting to resolve the url-token.
if (args.kind !== 'url-token' || args.pluginData?.[CSS_RESOURCE_RESOLUTION]) {
if (kind !== 'url-token' || pluginData[CSS_RESOURCE_RESOLUTION]) {
return null;
}

let [containingDir, resourceUrl] = path.split('||file:', 2);
if (resourceUrl === undefined) {
// This can happen due to early exit checks in rebasing-importer
// logic such as when the url is an external URL.
resourceUrl = containingDir;
containingDir = '';
}

// If root-relative, absolute or protocol relative url, mark as external to leave the
// path/URL in place.
if (/^((?:\w+:)?\/\/|data:|chrome:|#|\/)/.test(args.path)) {
if (/^((?:\w+:)?\/\/|data:|chrome:|#|\/)/.test(resourceUrl)) {
return {
path: args.path,
path: resourceUrl,
external: true,
};
}

const { importer, kind, resolveDir, namespace, pluginData = {} } = args;
pluginData[CSS_RESOURCE_RESOLUTION] = true;

const result = await build.resolve(args.path, {
const result = await build.resolve(resourceUrl, {
importer,
kind,
namespace,
pluginData,
resolveDir,
resolveDir: join(resolveDir, containingDir),
});

if (result.errors.length) {
const error = result.errors[0];
if (args.path[0] === '~') {
if (resourceUrl[0] === '~') {
error.notes = [
{
location: null,
text: 'You can remove the tilde and use a relative path to reference it, which should remove this error.',
},
];
} else if (args.path[0] === '^') {
} else if (resourceUrl[0] === '^') {
error.notes = [
{
location: null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,18 +82,15 @@ abstract class UrlRebasingImporter implements Importer<'sync'> {
continue;
}

// Skip if value is a Sass variable.
// Sass variable usage either starts with a `$` or contains a namespace and a `.$`
if (value[0] === '$' || /^\w+\.\$/.test(value)) {
continue;
}

// Skip if root-relative, absolute or protocol relative url
if (/^((?:\w+:)?\/\/|data:|chrome:|#|\/)/.test(value)) {
continue;
}

const rebasedPath = relative(this.entryDirectory, join(stylesheetDirectory, value));
// Sass variable usage either starts with a `$` or contains a namespace and a `.$`
const valueNormalized = value[0] === '$' || /^\w+\.\$/.test(value) ? `#{${value}}` : value;
const rebasedPath =
relative(this.entryDirectory, stylesheetDirectory) + '||file:' + valueNormalized;

// Normalize path separators and escape characters
// https://developer.mozilla.org/en-US/docs/Web/CSS/url#syntax
Expand Down