utils.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { TransformAssetUrlsOptions } from './assetUrl'
  2. import { UrlWithStringQuery, parse as uriParse } from 'url'
  3. import path from 'path'
  4. export interface Attr {
  5. name: string
  6. value: string
  7. }
  8. export interface ASTNode {
  9. tag: string
  10. attrs: Attr[]
  11. }
  12. export function urlToRequire(
  13. url: string,
  14. transformAssetUrlsOption: TransformAssetUrlsOptions = {}
  15. ): string {
  16. const returnValue = `"${url}"`
  17. // same logic as in transform-require.js
  18. const firstChar = url.charAt(0)
  19. if (firstChar === '~') {
  20. const secondChar = url.charAt(1)
  21. url = url.slice(secondChar === '/' ? 2 : 1)
  22. }
  23. const uriParts = parseUriParts(url)
  24. if (transformAssetUrlsOption.base) {
  25. // explicit base - directly rewrite the url into absolute url
  26. // does not apply to absolute urls or urls that start with `@`
  27. // since they are aliases
  28. if (firstChar === '.' || firstChar === '~') {
  29. // when packaged in the browser, path will be using the posix-
  30. // only version provided by rollup-plugin-node-builtins.
  31. return `"${(path.posix || path).join(
  32. transformAssetUrlsOption.base,
  33. uriParts.path + (uriParts.hash || '')
  34. )}"`
  35. }
  36. return returnValue
  37. }
  38. if (firstChar === '.' || firstChar === '~' || firstChar === '@') {
  39. if (!uriParts.hash) {
  40. return `require("${url}")`
  41. } else {
  42. // support uri fragment case by excluding it from
  43. // the require and instead appending it as string;
  44. // assuming that the path part is sufficient according to
  45. // the above caseing(t.i. no protocol-auth-host parts expected)
  46. return `require("${uriParts.path}") + "${uriParts.hash}"`
  47. }
  48. }
  49. return returnValue
  50. }
  51. /**
  52. * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
  53. * @param urlString an url as a string
  54. */
  55. function parseUriParts(urlString: string): UrlWithStringQuery {
  56. // initialize return value
  57. const returnValue: UrlWithStringQuery = uriParse('')
  58. if (urlString) {
  59. // A TypeError is thrown if urlString is not a string
  60. // @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
  61. if ('string' === typeof urlString) {
  62. // check is an uri
  63. return uriParse(urlString) // take apart the uri
  64. }
  65. }
  66. return returnValue
  67. }