npm install @csstools/postcss-rewrite-url --save-dev
PostCSS Rewrite URL lets you rewrite url values in CSS.
.foo {
background: rewrite-url('foo.png');
}
@font-face {
font-family: "Trickster";
src:
local("Trickster"),
rewrite-url("trickster-COLRv1.otf") format("opentype");
}
/* becomes */
.foo {
background: url("foo.png#modified");
}
@font-face {
font-family: "Trickster";
src:
local("Trickster"),
url("trickster-COLRv1.otf#modified") format("opentype");
}
Add PostCSS Rewrite URL to your project:
npm install postcss @csstools/postcss-rewrite-url --save-dev
Use it as a PostCSS plugin:
const postcss = require('postcss');
const postcssRewriteURL = require('@csstools/postcss-rewrite-url');
postcss([
postcssRewriteURL(/* pluginOptions */)
]).process(YOUR_CSS /*, processOptions */);
Determine how urls are rewritten with the rewriter
callback.
export interface ValueToRewrite {
url: string
}
export interface RewriteContext {
type: 'declaration-value' | 'at-rule-prelude';
from: string | undefined;
rootFrom: string | undefined;
property?: string;
atRuleName?: string;
}
export type Rewriter = (value: ValueToRewrite, context: RewriteContext) => ValueToRewrite | false;
/** postcss-rewrite-url plugin options */
export type pluginOptions = {
rewriter: Rewriter;
};
postcssRewriteURL({
rewriter: (value, context) => {
if (value.url === 'ignore-me') {
// return `false` to ignore this url and preserve `rewrite-url()` in the output
return false;
}
console.log(context); // for extra conditional logic
return {
url: value.url + '#modified',
};
},
})