You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.3 KiB

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