utils.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { siteDataRef } from './data';
  2. import { inBrowser, EXTERNAL_URL_RE } from '../shared';
  3. export { inBrowser };
  4. /**
  5. * Join two paths by resolving the slash collision.
  6. */
  7. export function joinPath(base, path) {
  8. return `${base}${path}`.replace(/\/+/g, '/');
  9. }
  10. export function withBase(path) {
  11. return EXTERNAL_URL_RE.test(path)
  12. ? path
  13. : joinPath(siteDataRef.value.base, path);
  14. }
  15. /**
  16. * Converts a url path to the corresponding js chunk filename.
  17. */
  18. export function pathToFile(path) {
  19. let pagePath = path.replace(/\.html$/, '');
  20. pagePath = decodeURIComponent(pagePath);
  21. if (pagePath.endsWith('/')) {
  22. pagePath += 'index';
  23. }
  24. if (import.meta.env.DEV) {
  25. // always force re-fetch content in dev
  26. pagePath += `.md?t=${Date.now()}`;
  27. }
  28. else {
  29. // in production, each .md file is built into a .md.js file following
  30. // the path conversion scheme.
  31. // /foo/bar.html -> ./foo_bar.md
  32. if (inBrowser) {
  33. const base = import.meta.env.BASE_URL;
  34. pagePath = pagePath.slice(base.length).replace(/\//g, '_') + '.md';
  35. // client production build needs to account for page hash, which is
  36. // injected directly in the page's html
  37. const pageHash = __VP_HASH_MAP__[pagePath.toLowerCase()];
  38. pagePath = `${base}assets/${pagePath}.${pageHash}.js`;
  39. }
  40. else {
  41. // ssr build uses much simpler name mapping
  42. pagePath = `./${pagePath.slice(1).replace(/\//g, '_')}.md.js`;
  43. }
  44. }
  45. return pagePath;
  46. }