Skip to content

Commit 2714c6b

Browse files
committed
feat: add emits declaration
1 parent 121c571 commit 2714c6b

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* @param {Object} context
3+
* @param {import('jscodeshift').JSCodeshift} context.j
4+
* @param {ReturnType<import('jscodeshift').Core>} context.root
5+
*/
6+
module.exports = function addEmitDeclaration(context) {
7+
const { j, root } = context
8+
9+
// this.$emit('xxx') => emits: ['xxx']
10+
const this$emits = root.find(j.CallExpression, {
11+
callee: {
12+
type: 'MemberExpression',
13+
object: { type: 'ThisExpression' },
14+
property: {
15+
type: 'Identifier',
16+
name: '$emit'
17+
}
18+
}
19+
})
20+
21+
const emits = []
22+
for (let i = 0; i < this$emits.length; i++) {
23+
const arg = this$emits.at(i).get().node.arguments[0]
24+
if (arg.type === 'StringLiteral') {
25+
emits.push(arg.value)
26+
}
27+
}
28+
29+
if (emits.length === 0) {
30+
return
31+
}
32+
33+
const properties = root
34+
.find(j.ExportDefaultDeclaration)
35+
.at(0)
36+
.find(j.ObjectExpression)
37+
.at(0)
38+
39+
properties.replaceWith(nodePath => {
40+
nodePath.node.properties.unshift(
41+
j.objectProperty(
42+
j.identifier('emits'),
43+
j.arrayExpression(emits.map(el => j.stringLiteral(el)))
44+
)
45+
)
46+
return nodePath.node
47+
})
48+
}

generator/codemods/vue/index.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/** @type {import('jscodeshift').Transform} */
2+
module.exports = function(fileInfo, api) {
3+
const j = api.jscodeshift
4+
const root = j(fileInfo.source)
5+
const context = { j, root }
6+
7+
require('./add-emit-declaration')(context)
8+
9+
return root.toSource({ lineTerminator: '\n' })
10+
}
11+
12+
module.exports.parser = 'babylon'

generator/index.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,14 @@ module.exports = (api) => {
2222
const globalAPITransform = require('./codemods/global-api')
2323
api.transformScript(api.entryFile, globalAPITransform)
2424

25+
const vueTransform = require('./codemods/vue')
26+
const vueFiles = Object.keys(api.generator.files).filter(el =>
27+
el.endsWith('.vue')
28+
)
29+
for (let i = 0; i < vueFiles.length; i++) {
30+
api.transformScript(vueFiles[i], vueTransform)
31+
}
32+
2533
if (api.hasPlugin('eslint')) {
2634
api.extendPackage({
2735
devDependencies: {

0 commit comments

Comments
 (0)