postcss / postcss-url

PostCSS plugin to rebase url(), inline or copy asset.
MIT License
377 stars 60 forks source link

Can't resolve absolute paths when prefixed with `~` in scss files #176

Open juzerzarif opened 2 years ago

juzerzarif commented 2 years ago

I have a font-face block as follows:

@font-face {
  font-family: 'FontAwesome';
  src: url('~font-awesome/fonts/fontawesome-webfont.eot?v=4.7.0');
  src: url('~font-awesome/fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype');
  font-weight: normal;
  font-style: normal;
}

postcss-url can't seem to resolve ~font-awesome/fonts/fontawesome-webfont.eot to the correct node_modules path and resolves it relative to the scss file that's being transformed i.e. /Users/me/my-project/src/~font-awesome/fonts/fontawesome-webfont.eot which causes inlining to not work since there's no font file at that path.

Is there a way to have postcss-url resolve ~ prefixed paths from node_modules instead of relative to the scss file?

RolKau commented 10 months ago

You could use the rewrite functionality to insert the path to the module relative to the stylesheet:

import path from 'node:path';
import url from 'postcss-url';

url({
    filter: (asset) => /^~/.exec(asset.url),
    url: (asset, dir) => path.join(path.relative(dir.from, path.join(__dirname, 'node_modules')), asset.url.substr(1)),
})