assetUrl.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // vue compiler module for transforming `<tag>:<attribute>` to `require`
  2. import { urlToRequire, ASTNode, Attr } from './utils'
  3. export interface AssetURLOptions {
  4. [name: string]: string | string[]
  5. }
  6. export interface TransformAssetUrlsOptions {
  7. /**
  8. * If base is provided, instead of transforming relative asset urls into
  9. * imports, they will be directly rewritten to absolute urls.
  10. */
  11. base?: string
  12. }
  13. const defaultOptions: AssetURLOptions = {
  14. audio: 'src',
  15. video: ['src', 'poster'],
  16. source: 'src',
  17. img: 'src',
  18. image: ['xlink:href', 'href'],
  19. use: ['xlink:href', 'href']
  20. }
  21. export default (
  22. userOptions?: AssetURLOptions,
  23. transformAssetUrlsOption?: TransformAssetUrlsOptions
  24. ) => {
  25. const options = userOptions
  26. ? Object.assign({}, defaultOptions, userOptions)
  27. : defaultOptions
  28. return {
  29. postTransformNode: (node: ASTNode) => {
  30. transform(node, options, transformAssetUrlsOption)
  31. }
  32. }
  33. }
  34. function transform(
  35. node: ASTNode,
  36. options: AssetURLOptions,
  37. transformAssetUrlsOption?: TransformAssetUrlsOptions
  38. ) {
  39. for (const tag in options) {
  40. if ((tag === '*' || node.tag === tag) && node.attrs) {
  41. const attributes = options[tag]
  42. if (typeof attributes === 'string') {
  43. node.attrs.some(attr =>
  44. rewrite(attr, attributes, transformAssetUrlsOption)
  45. )
  46. } else if (Array.isArray(attributes)) {
  47. attributes.forEach(item =>
  48. node.attrs.some(attr => rewrite(attr, item, transformAssetUrlsOption))
  49. )
  50. }
  51. }
  52. }
  53. }
  54. function rewrite(
  55. attr: Attr,
  56. name: string,
  57. transformAssetUrlsOption?: TransformAssetUrlsOptions
  58. ) {
  59. if (attr.name === name) {
  60. const value = attr.value
  61. // only transform static URLs
  62. if (value.charAt(0) === '"' && value.charAt(value.length - 1) === '"') {
  63. attr.value = urlToRequire(value.slice(1, -1), transformAssetUrlsOption)
  64. return true
  65. }
  66. }
  67. return false
  68. }