injectOptions.js 845 B

123456789101112131415161718192021222324252627
  1. module.exports = function injectOptions (fileInfo, api, { injections }) {
  2. const j = api.jscodeshift
  3. const root = j(fileInfo.source)
  4. const toPropertyAST = i => {
  5. return j(`({${i}})`).nodes()[0].program.body[0].expression.properties[0]
  6. }
  7. const properties = root
  8. .find(j.NewExpression, {
  9. callee: { name: 'Vue' },
  10. arguments: [{ type: 'ObjectExpression' }]
  11. })
  12. .map(path => path.get('arguments', 0))
  13. .get()
  14. .node
  15. .properties
  16. const toPropertyHash = p => `${p.key.name}: ${j(p.value).toSource()}`
  17. const propertySet = new Set(properties.map(toPropertyHash))
  18. const nonDuplicates = p => !propertySet.has(toPropertyHash(p))
  19. // inject at index length - 1 as it's usually the render fn
  20. properties.splice(-1, 0, ...injections.map(toPropertyAST).filter(nonDuplicates))
  21. return root.toSource()
  22. }