templateTransformAssetUrl.spec.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { generate, baseParse, transform } from '@vue/compiler-core'
  2. import {
  3. transformAssetUrl,
  4. createAssetUrlTransformWithOptions,
  5. AssetURLOptions,
  6. normalizeOptions
  7. } from '../src/templateTransformAssetUrl'
  8. import { transformElement } from '../../compiler-core/src/transforms/transformElement'
  9. import { transformBind } from '../../compiler-core/src/transforms/vBind'
  10. function compileWithAssetUrls(template: string, options?: AssetURLOptions) {
  11. const ast = baseParse(template)
  12. const t = options
  13. ? createAssetUrlTransformWithOptions(normalizeOptions(options))
  14. : transformAssetUrl
  15. transform(ast, {
  16. nodeTransforms: [t, transformElement],
  17. directiveTransforms: {
  18. bind: transformBind
  19. }
  20. })
  21. return generate(ast, { mode: 'module' })
  22. }
  23. describe('compiler sfc: transform asset url', () => {
  24. test('transform assetUrls', () => {
  25. const result = compileWithAssetUrls(`
  26. <img src="./logo.png"/>
  27. <img src="~fixtures/logo.png"/>
  28. <img src="~/fixtures/logo.png"/>
  29. <img src="http://example.com/fixtures/logo.png"/>
  30. <img src="/fixtures/logo.png"/>
  31. `)
  32. expect(result.code).toMatchSnapshot()
  33. })
  34. /**
  35. * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
  36. */
  37. test('support uri fragment', () => {
  38. const result = compileWithAssetUrls(
  39. '<use href="~@svg/file.svg#fragment"></use>'
  40. )
  41. expect(result.code).toMatchSnapshot()
  42. })
  43. /**
  44. * vuejs/component-compiler-utils#22 Support uri fragment in transformed require
  45. */
  46. test('support uri is empty', () => {
  47. const result = compileWithAssetUrls('<use href="~"></use>')
  48. expect(result.code).toMatchSnapshot()
  49. })
  50. test('with explicit base', () => {
  51. const { code } = compileWithAssetUrls(
  52. `<img src="./bar.png"></img>` + // -> /foo/bar.png
  53. `<img src="~bar.png"></img>` + // -> /foo/bar.png
  54. `<img src="bar.png"></img>` + // -> bar.png (untouched)
  55. `<img src="@theme/bar.png"></img>`, // -> @theme/bar.png (untouched)
  56. {
  57. base: '/foo'
  58. }
  59. )
  60. expect(code).toMatchSnapshot()
  61. })
  62. test('with includeAbsolute: true', () => {
  63. const { code } = compileWithAssetUrls(
  64. `<img src="./bar.png"/>` +
  65. `<img src="/bar.png"/>` +
  66. `<img src="https://foo.bar/baz.png"/>`,
  67. {
  68. includeAbsolute: true
  69. }
  70. )
  71. expect(code).toMatchSnapshot()
  72. })
  73. })