templateUtils.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { type UrlWithStringQuery, parse as uriParse } from 'url'
  2. import { isString } from '@vue/shared'
  3. export function isRelativeUrl(url: string): boolean {
  4. const firstChar = url.charAt(0)
  5. return (
  6. firstChar === '.' ||
  7. firstChar === '~' ||
  8. firstChar === '@' ||
  9. firstChar === '#'
  10. )
  11. }
  12. const externalRE = /^(?:https?:)?\/\//
  13. export function isExternalUrl(url: string): boolean {
  14. return externalRE.test(url)
  15. }
  16. const dataUrlRE = /^\s*data:/i
  17. export function isDataUrl(url: string): boolean {
  18. return dataUrlRE.test(url)
  19. }
  20. export function normalizeDecodedImportPath(source: string): string {
  21. try {
  22. return decodeURIComponent(source)
  23. } catch {
  24. return source
  25. }
  26. }
  27. /**
  28. * Parses string url into URL object.
  29. */
  30. export function parseUrl(url: string): UrlWithStringQuery {
  31. const firstChar = url.charAt(0)
  32. if (firstChar === '~') {
  33. const secondChar = url.charAt(1)
  34. url = url.slice(secondChar === '/' ? 2 : 1)
  35. }
  36. return parseUriParts(url)
  37. }
  38. /**
  39. * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
  40. * @param urlString - an url as a string
  41. */
  42. function parseUriParts(urlString: string): UrlWithStringQuery {
  43. // A TypeError is thrown if urlString is not a string
  44. // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
  45. return uriParse(isString(urlString) ? urlString : '', false, true)
  46. }