transform-require.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // vue compiler module for transforming `<tag>:<attribute>` to `require`
  2. const urlToRequire = require('../url-to-require')
  3. const defaultOptions = {
  4. video: ['src', 'poster'],
  5. source: 'src',
  6. img: 'src',
  7. image: 'xlink:href'
  8. }
  9. module.exports = userOptions => {
  10. const options = userOptions
  11. ? Object.assign({}, defaultOptions, userOptions)
  12. : defaultOptions
  13. return {
  14. postTransformNode: node => {
  15. transform(node, options)
  16. }
  17. }
  18. }
  19. function transform (node, options) {
  20. for (const tag in options) {
  21. if ((tag === '*' || node.tag === tag) && node.attrs) {
  22. const attributes = options[tag]
  23. if (typeof attributes === 'string') {
  24. node.attrs.some(attr => rewrite(attr, attributes))
  25. } else if (Array.isArray(attributes)) {
  26. attributes.forEach(item => node.attrs.some(attr => rewrite(attr, item)))
  27. }
  28. }
  29. }
  30. }
  31. function rewrite (attr, name) {
  32. if (attr.name === name) {
  33. const value = attr.value
  34. // only transform static URLs
  35. if (value.charAt(0) === '"' && value.charAt(value.length - 1) === '"') {
  36. attr.value = urlToRequire(value.slice(1, -1))
  37. return true
  38. }
  39. }
  40. }