Skip to content

Commit 0e92531

Browse files
committed
fix(codemods): fails to add Vite plugin when using defineConfig
1 parent eb0734a commit 0e92531

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

src/code_transformer/main.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -401,9 +401,15 @@ export class CodeTransformer {
401401
throw new Error('Cannot find the default export in vite.config.ts')
402402
}
403403

404-
const options = defaultExport
405-
.getDeclarations()[0]
406-
.getChildrenOfKind(SyntaxKind.ObjectLiteralExpression)[0]
404+
/**
405+
* Get the options object
406+
* - Either the first argument of `defineConfig` call : `export default defineConfig({})`
407+
* - Or child literal expression of the default export : `export default {}`
408+
*/
409+
const declaration = defaultExport.getDeclarations()[0]
410+
const options =
411+
declaration.getChildrenOfKind(SyntaxKind.ObjectLiteralExpression)[0] ||
412+
declaration.getChildrenOfKind(SyntaxKind.CallExpression)[0].getArguments()[0]
407413

408414
const pluginsArray = options
409415
.getPropertyOrThrow('plugins')

tests/code_transformer.spec.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -842,6 +842,38 @@ test.group('Code transformer | addVitePlugin', (group) => {
842842
`)
843843
})
844844

845+
test('insert in defineConfig call', async ({ assert, fs }) => {
846+
await fs.create(
847+
'vite.config.ts',
848+
`export default defineConfig({
849+
plugins: [],
850+
})`
851+
)
852+
853+
const transformer = new CodeTransformer(fs.baseUrl)
854+
855+
await transformer.addVitePlugin('vue({ foo: 32 })', [
856+
{ identifier: 'vue', module: 'vue', isNamed: false },
857+
{ identifier: 'foo', module: 'foo', isNamed: true },
858+
])
859+
860+
await transformer.addVitePlugin('vue({ foo: 32 })', [
861+
{ identifier: 'vue', module: 'vue', isNamed: false },
862+
{ identifier: 'foo', module: 'foo', isNamed: true },
863+
])
864+
865+
const file = await fs.contents('vite.config.ts')
866+
assert.snapshot(file).matchInline(`
867+
"import vue from 'vue'
868+
import { foo } from 'foo'
869+
870+
export default defineConfig({
871+
plugins: [vue({ foo: 32 })],
872+
})
873+
"
874+
`)
875+
})
876+
845877
test('throw error when vite.config.ts file is missing', async ({ fs }) => {
846878
const transformer = new CodeTransformer(fs.baseUrl)
847879

0 commit comments

Comments
 (0)