complately update relative path regexp

This commit is contained in:
Yanzhen Yu
2026-04-01 12:00:00 +08:00
parent cf54d7dab5
commit cdedca1716
3 changed files with 9 additions and 2 deletions

View File

@@ -40,7 +40,7 @@
"chai": "^4.1.2",
"jest-snapshot": "^23.6.0",
"mocha": "^5.2.0",
"puppeteer": "^1.9.0",
"puppeteer": "^1.10.0",
"rollup": "^0.66.4",
"rollup-plugin-terser": "^3.0.0",
"rollup-plugin-typescript": "^1.0.0",

View File

@@ -43,9 +43,10 @@ function extractOrigin(url: string): string {
}
const URL_IN_CSS_REF = /url\((['"]|)([^'"]*)\1\)/gm;
const RELATIVE_PATH = /^(?!www\.|(?:http|ftp)s?:\/\/|[A-Za-z]:\\|\/\/).*/;
export function absoluteToStylesheet(cssText: string, href: string): string {
return cssText.replace(URL_IN_CSS_REF, (_1, _2, filePath) => {
if (!/^[./]/.test(filePath)) {
if (!RELATIVE_PATH.test(filePath)) {
return `url('${filePath}')`;
}
if (filePath[0] === '/') {

View File

@@ -5,6 +5,12 @@ import { absoluteToStylesheet } from '../src/snapshot';
describe('absolute url to stylesheet', () => {
const href = 'http://localhost/css/style.css';
it('cam handle relative path', () => {
expect(absoluteToStylesheet('url(a.jpg)', href)).to.equal(
`url('http://localhost/css/a.jpg')`,
);
});
it('can handle same level path', () => {
expect(absoluteToStylesheet('url("./a.jpg")', href)).to.equal(
`url('http://localhost/css/a.jpg')`,