Skip to content

broken scss url rewrites with scss variables #5337

@gluck

Description

@gluck

Describe the bug

When an imported scss file has variable url($foo) links, they get badly rewritten:

scss-import-test/index.scss:

$default-image-1: "/default.png";
$default-image-2: "./default.png";
$default-image-3: "default.png";

body {
  background-image: url($default-image-1);
  background-image: url($default-image-2);
  background-image: url($default-image-3);
  background-image: url("/default.png");
  background-image: url("./default.png");
  background-image: url("default.png");
}

Gets rewritten as (notice the invalid css):

body {
  background-image: url(node_modules/scss-import-test/"/default.png"); // NOK
  background-image: url(node_modules/scss-import-test/"./default.png"); // NOK
  background-image: url(node_modules/scss-import-test/"default.png"); // NOK
  background-image: url("/default.png");
  background-image: url("/node_modules/scss-import-test/default.png"); // OK
  background-image: url("/node_modules/scss-import-test/default.png"); // OK
}

Note that when imported through another (intermediate) scss file, the output is different:
scss-import-test/nested.scss:

@import './index.scss'

Results into (valid css, but the paths aren't rewritten):

body {
  background-image: url("/default.png");
  background-image: url("./default.png");
  background-image: url("default.png");
  background-image: url("/default.png");
  background-image: url("./default.png");
  background-image: url("default.png");
}

I believe this erratic behavior is caused by rebaseUrls/rewriteCssUrls being executed on (raw SCSS) content from the first import from src (and only the first, further imports will get processed by vite-url-rewrite postcss plugin, on CSS ast, with variable interpolated), can probably submit a PR if agreed.

Reproduction

https://stackblitz.com/edit/vite-dgawmt?file=index.scss

System Info

Stackbliz doesn't run envinfo.
vite@2.6.9

Used Package Manager

npm

Logs

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions