|
| 1 | +const addImport = require('../utils/add-import') |
| 2 | +const removeExtraneousImport = require('../utils/remove-extraneous-import') |
| 3 | + |
1 | 4 | /** @type {import('jscodeshift').Transform} */
|
2 | 5 | module.exports = function(fileInfo, api) {
|
3 | 6 | const j = api.jscodeshift
|
4 | 7 | const root = j(fileInfo.source)
|
| 8 | + const context = { j, root } |
| 9 | + |
| 10 | + // TODO: new Store() -> createStore() |
| 11 | + |
| 12 | + const vuexImportDecls = root.find(j.ImportDeclaration, { |
| 13 | + source: { |
| 14 | + value: 'vuex' |
| 15 | + } |
| 16 | + }) |
| 17 | + |
| 18 | + const importedVuex = vuexImportDecls.find(j.ImportDefaultSpecifier) |
| 19 | + const importedStore = vuexImportDecls.find(j.ImportSpecifier, { |
| 20 | + imported: { |
| 21 | + name: 'Store' |
| 22 | + } |
| 23 | + }) |
| 24 | + |
| 25 | + if (importedVuex.length) { |
| 26 | + const localVuex = importedVuex.get(0).node.local.name |
| 27 | + const newVuexDotStore = root.find(j.NewExpression, { |
| 28 | + callee: { |
| 29 | + type: 'MemberExpression', |
| 30 | + object: { |
| 31 | + type: 'Identifier', |
| 32 | + name: localVuex |
| 33 | + }, |
| 34 | + property: { |
| 35 | + name: 'Store' |
| 36 | + } |
| 37 | + } |
| 38 | + }) |
| 39 | + |
| 40 | + newVuexDotStore.replaceWith(({ node }) => { |
| 41 | + return j.callExpression( |
| 42 | + j.memberExpression( |
| 43 | + j.identifier(localVuex), |
| 44 | + j.identifier('createStore') |
| 45 | + ), |
| 46 | + node.arguments |
| 47 | + ) |
| 48 | + }) |
| 49 | + } |
| 50 | + |
| 51 | + if (importedStore.length) { |
| 52 | + const localStore = importedStore.get(0).node.local.name |
| 53 | + const newStore = root.find(j.NewExpression, { |
| 54 | + callee: { |
| 55 | + type: 'Identifier', |
| 56 | + name: localStore |
| 57 | + } |
| 58 | + }) |
| 59 | + |
| 60 | + addImport(context, { imported: 'createStore' }, 'vuex') |
| 61 | + newStore.replaceWith(({ node }) => { |
| 62 | + return j.callExpression(j.identifier('createStore'), node.arguments) |
| 63 | + }) |
| 64 | + removeExtraneousImport(context, localStore) |
| 65 | + } |
5 | 66 |
|
6 | 67 | return root.toSource({ lineTerminator: '\n' })
|
7 | 68 | }
|
0 commit comments