Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: support parser option for codemods, and enable ts parsing by default #4883

Merged
merged 1 commit into from Nov 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
}