Skip to content

Commit

Permalink
fix: support parser option for codemods, and enable ts parsing by d…
Browse files Browse the repository at this point in the history
…efault (#4883)

fixes #4861
  • Loading branch information
sodatea committed Nov 26, 2019
1 parent ef2cbae commit b7f83b4
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
18 changes: 18 additions & 0 deletions packages/@vue/cli/__tests__/Generator.spec.js
Expand Up @@ -23,6 +23,7 @@ new Vue({
}).$mount('#app')
`.trim())
fs.writeFileSync(path.resolve(templateDir, 'empty-entry.js'), `;`)
fs.writeFileSync(path.resolve(templateDir, 'main.ts'), `const a: string = 'hello';`)
fs.writeFileSync(path.resolve(templateDir, 'hello.vue'), `
<template>
<p>Hello, {{ msg }}</p>
Expand Down Expand Up @@ -530,6 +531,23 @@ test('api: injectImports to empty file', async () => {
expect(fs.readFileSync('/main.js', 'utf-8')).toMatch(/import foo from 'foo'\r?\nimport bar from 'bar'/)
})

test('api: injectImports to typescript file', async () => {
const generator = new Generator('/', { plugins: [
{
id: 'test',
apply: api => {
api.injectImports('main.ts', `import foo from 'foo'`)
api.render({
'main.ts': path.join(templateDir, 'main.ts')
})
}
}
] })

await generator.generate()
expect(fs.readFileSync('/main.ts', 'utf-8')).toMatch(/import foo from 'foo'/)
})

test('api: addEntryDuplicateImport', async () => {
const generator = new Generator('/', { plugins: [
{
Expand Down
30 changes: 27 additions & 3 deletions packages/@vue/cli/lib/util/runCodemod.js
@@ -1,6 +1,30 @@
const jscodeshift = require('jscodeshift')
const adapt = require('vue-jscodeshift-adapter')
let jscodeshift = require('jscodeshift')

module.exports = function runCodemod (transform, fileInfo, options) {
return adapt(transform)(fileInfo, { jscodeshift }, options || {})
module.exports = function runCodemod (transformModule, fileInfo, options = {}) {
const transform = typeof transformModule.default === 'function'
? transformModule.default
: transformModule

let parser = transformModule.parser || options.parser
if (!parser) {
if (fileInfo.path.endsWith(('.ts'))) {
parser = 'ts'
} else if (fileInfo.path.endsWith('.tsx')) {
parser = 'tsx'
}
}

if (parser) {
jscodeshift = jscodeshift.withParser(parser)
}

const api = {
jscodeshift,
j: jscodeshift,
stats: () => {},
report: () => {}
}

return adapt(transform)(fileInfo, api, options)
}

0 comments on commit b7f83b4

Please sign in to comment.