|
| 1 | +module.exports = function injectImportsAndOptions (source, imports, injections) { |
| 2 | + imports = imports instanceof Set ? Array.from(imports) : imports |
| 3 | + injections = injections instanceof Set ? Array.from(injections) : injections |
| 4 | + |
| 5 | + const hasImports = imports && imports.length > 0 |
| 6 | + const hasInjections = injections && injections.length > 0 |
| 7 | + |
| 8 | + if (!hasImports && !hasInjections) { |
| 9 | + return source |
| 10 | + } |
| 11 | + |
| 12 | + const recast = require('recast') |
| 13 | + const ast = recast.parse(source) |
| 14 | + |
| 15 | + if (hasImports) { |
| 16 | + const toImport = i => recast.parse(`${i}\n`).program.body[0] |
| 17 | + let lastImportIndex = -1 |
| 18 | + recast.types.visit(ast, { |
| 19 | + visitImportDeclaration ({ node }) { |
| 20 | + lastImportIndex = ast.program.body.findIndex(n => n === node) |
| 21 | + return false |
| 22 | + } |
| 23 | + }) |
| 24 | + // avoid blank line after the previous import |
| 25 | + delete ast.program.body[lastImportIndex].loc |
| 26 | + |
| 27 | + const newImports = imports.map(toImport) |
| 28 | + ast.program.body.splice(lastImportIndex + 1, 0, ...newImports) |
| 29 | + } |
| 30 | + |
| 31 | + if (hasInjections) { |
| 32 | + const toProperty = i => { |
| 33 | + return recast.parse(`({${i}})`).program.body[0].expression.properties |
| 34 | + } |
| 35 | + recast.types.visit(ast, { |
| 36 | + visitNewExpression ({ node }) { |
| 37 | + if (node.callee.name === 'Vue') { |
| 38 | + const options = node.arguments[0] |
| 39 | + if (options && options.type === 'ObjectExpression') { |
| 40 | + const props = options.properties |
| 41 | + // inject at index length - 1 as it's usually the render fn |
| 42 | + options.properties = [ |
| 43 | + ...props.slice(0, props.length - 1), |
| 44 | + ...([].concat(...injections.map(toProperty))), |
| 45 | + ...props.slice(props.length - 1) |
| 46 | + ] |
| 47 | + } |
| 48 | + } |
| 49 | + return false |
| 50 | + } |
| 51 | + }) |
| 52 | + } |
| 53 | + |
| 54 | + return recast.print(ast).code |
| 55 | +} |
0 commit comments