Skip to content

Commit

Permalink
Merge branch 'main' into remove_doc_generator_0829
Browse files Browse the repository at this point in the history
  • Loading branch information
chenjiahan authored Aug 29, 2023
2 parents ef7fc89 + c9ffc4d commit 2a8701b
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 22 deletions.
7 changes: 7 additions & 0 deletions .changeset/few-olives-remain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@modern-js/builder-shared': patch
---

fix(builder): fix withPublicPath may missing subpath

fix(builder): 修复 withPublicPath 方法可能会丢失子路径的问题
20 changes: 1 addition & 19 deletions packages/builder/builder-shared/src/url.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { URL } from 'url';
import path from 'path';
import { urlJoin } from '@modern-js/utils';

export const withPublicPath = (str: string, base: string) => {
Expand All @@ -11,28 +10,11 @@ export const withPublicPath = (str: string, base: string) => {
return str;
}

if (base.startsWith('//')) {
return urlJoin(base, str);
}

// Only absolute url with hostname & protocol can be parsed into URL instance.
// e.g. str is https://example.com/foo.js
try {
return new URL(str).toString();
} catch {}

// Or it should be a relative path.
// Let's join the publicPath.
// e.g. str is ./foo.js
try {
// `base` is a url with hostname & protocol.
// e.g. base is https://example.com/static
const url = new URL(base);
url.pathname = path.posix.resolve(url.pathname, str);
return url.toString();
} catch {
// without hostname & protocol.
// e.g. base is /
return path.posix.resolve(base, str);
}
return urlJoin(base, str);
};
6 changes: 3 additions & 3 deletions packages/builder/builder-shared/tests/url.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ describe('withPublicPath', () => {
'https://www.example.com/static/foo/bar.js',
);
expect(withPublicPath('foo/bar.js', '/')).toBe('/foo/bar.js');
expect(withPublicPath('./foo/bar.js', PUBLIC_PATH)).toBe(
expect(withPublicPath('/foo/bar.js', PUBLIC_PATH)).toBe(
'https://www.example.com/static/foo/bar.js',
);
expect(withPublicPath('./foo/bar.js', '/')).toBe('/foo/bar.js');
expect(withPublicPath('/foo/bar.js', '/')).toBe('/foo/bar.js');
});

it('should handle absolute url', () => {
expect(withPublicPath('/foo/bar.js', PUBLIC_PATH)).toBe(
'https://www.example.com/foo/bar.js',
'https://www.example.com/static/foo/bar.js',
);
expect(withPublicPath('/foo/bar.js', '/')).toBe('/foo/bar.js');
});
Expand Down

0 comments on commit 2a8701b

Please sign in to comment.