assetUrl.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. const defaultOptions: AssetURLOptions = {
  7. audio: 'src',
  8. video: ['src', 'poster'],
  9. source: 'src',
  10. img: 'src',
  11. image: ['xlink:href', 'href'],
  12. use: ['xlink:href', 'href']
  13. }
  14. export default (userOptions?: AssetURLOptions) => {
  15. const options = userOptions
  16. ? Object.assign({}, defaultOptions, userOptions)
  17. : defaultOptions
  18. return {
  19. postTransformNode: (node: ASTNode) => {
  20. transform(node, options)
  21. }
  22. }
  23. }
  24. function transform(node: ASTNode, options: AssetURLOptions) {
  25. for (const tag in options) {
  26. if ((tag === '*' || node.tag === tag) && node.attrs) {
  27. const attributes = options[tag]
  28. if (typeof attributes === 'string') {
  29. node.attrs.some(attr => rewrite(attr, attributes))
  30. } else if (Array.isArray(attributes)) {
  31. attributes.forEach(item => node.attrs.some(attr => rewrite(attr, item)))
  32. }
  33. }
  34. }
  35. }
  36. function rewrite(attr: Attr, name: string) {
  37. if (attr.name === name) {
  38. const value = attr.value
  39. // only transform static URLs
  40. if (value.charAt(0) === '"' && value.charAt(value.length - 1) === '"') {
  41. attr.value = urlToRequire(value.slice(1, -1))
  42. return true
  43. }
  44. }
  45. return false
  46. }