|
| 1 | +// `shims-vue.d.ts` for Vue 3, generated by CLI 4.5.0-4.5.6, uses the following declaration: |
| 2 | +// `component: ReturnType<typeof defineComponent>` |
| 3 | + |
| 4 | +// So needs to update to: |
| 5 | +// `component: DefineComponent` |
| 6 | + |
| 7 | +module.exports = function migrateComponentType (file, api) { |
| 8 | + const j = api.jscodeshift |
| 9 | + const root = j(file.source) |
| 10 | + |
| 11 | + const useDoubleQuote = root.find(j.StringLiteral).some(({ node }) => node.extra.raw.startsWith('"')) |
| 12 | + |
| 13 | + const tsmodule = root.find(j.TSModuleDeclaration, { |
| 14 | + id: { |
| 15 | + value: '*.vue' |
| 16 | + } |
| 17 | + }) |
| 18 | + |
| 19 | + const componentDecl = tsmodule.find(j.VariableDeclarator, { |
| 20 | + id: { |
| 21 | + name: 'component', |
| 22 | + typeAnnotation: { |
| 23 | + typeAnnotation: { |
| 24 | + typeName: { |
| 25 | + name: 'ReturnType' |
| 26 | + }, |
| 27 | + typeParameters: { |
| 28 | + params: { |
| 29 | + 0: { |
| 30 | + exprName: { |
| 31 | + name: 'defineComponent' |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + }) |
| 40 | + |
| 41 | + if (componentDecl.length !== 1) { |
| 42 | + return file.source |
| 43 | + } |
| 44 | + |
| 45 | + // update the component type |
| 46 | + componentDecl.forEach(({ node }) => { |
| 47 | + node.id.typeAnnotation = j.tsTypeAnnotation( |
| 48 | + j.tsTypeReference(j.identifier('DefineComponent')) |
| 49 | + ) |
| 50 | + }) |
| 51 | + |
| 52 | + // insert DefineComponent type import |
| 53 | + const importDeclFromVue = tsmodule.find(j.ImportDeclaration, { |
| 54 | + source: { |
| 55 | + value: 'vue' |
| 56 | + } |
| 57 | + }) |
| 58 | + importDeclFromVue |
| 59 | + .get(0) |
| 60 | + .node.specifiers.push(j.importSpecifier(j.identifier('DefineComponent'))) |
| 61 | + |
| 62 | + // remove defineComponent import if unused |
| 63 | + const defineComponentUsages = tsmodule |
| 64 | + .find(j.Identifier, { name: 'defineComponent' }) |
| 65 | + .filter((identifierPath) => { |
| 66 | + const parent = identifierPath.parent.node |
| 67 | + |
| 68 | + // Ignore the import specifier |
| 69 | + if ( |
| 70 | + j.ImportDefaultSpecifier.check(parent) || |
| 71 | + j.ImportSpecifier.check(parent) || |
| 72 | + j.ImportNamespaceSpecifier.check(parent) |
| 73 | + ) { |
| 74 | + return false |
| 75 | + } |
| 76 | + }) |
| 77 | + if (defineComponentUsages.length === 0) { |
| 78 | + tsmodule |
| 79 | + .find(j.ImportSpecifier, { |
| 80 | + local: { |
| 81 | + name: 'defineComponent' |
| 82 | + } |
| 83 | + }) |
| 84 | + .remove() |
| 85 | + } |
| 86 | + |
| 87 | + return root.toSource({ |
| 88 | + lineTerminator: '\n', |
| 89 | + quote: useDoubleQuote ? 'double' : 'single' |
| 90 | + }) |
| 91 | +} |
| 92 | + |
| 93 | +module.exports.parser = 'ts' |
0 commit comments