Skip to content

Commit

Permalink
feat: add transformScript to GeneratorAPI (#4188)
Browse files Browse the repository at this point in the history
  • Loading branch information
sodatea committed Jun 26, 2019
1 parent 77092b2 commit 5460ca4
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
33 changes: 33 additions & 0 deletions packages/@vue/cli/__tests__/Generator.spec.js
Expand Up @@ -727,3 +727,36 @@ test('generate a JS-Only value from a string', async () => {
expect(generator.pkg).toHaveProperty('testScript')
expect(typeof generator.pkg.testScript).toBe('function')
})

test('run a codemod on the entry file', async () => {
// A test codemod that tranforms `new Vue` to `new TestVue`
const codemod = (fileInfo, api) => {
const j = api.jscodeshift
return j(fileInfo.source)
.find(j.NewExpression, {
callee: { name: 'Vue' },
arguments: [{ type: 'ObjectExpression' }]
})
.replaceWith(({ node }) => {
node.callee.name = 'TestVue'
return node
})
.toSource()
}

const generator = new Generator('/', { plugins: [
{
id: 'test',
apply: api => {
api.render({
'main.js': path.join(templateDir, 'entry.js')
})

api.transformScript('main.js', codemod)
}
}
] })

await generator.generate()
expect(fs.readFileSync('/main.js', 'utf-8')).toMatch(/new TestVue/)
})
17 changes: 17 additions & 0 deletions packages/@vue/cli/lib/GeneratorAPI.js
Expand Up @@ -6,6 +6,7 @@ const resolve = require('resolve')
const { isBinaryFileSync } = require('isbinaryfile')
const semver = require('semver')
const mergeDeps = require('./util/mergeDeps')
const runCodemod = require('./util/runCodemod')
const stringifyJS = require('./util/stringifyJS')
const ConfigTransform = require('./ConfigTransform')
const { getPluginLink, toShortPluginId, loadModule } = require('@vue/cli-shared-utils')
Expand Down Expand Up @@ -300,6 +301,22 @@ class GeneratorAPI {
return fn
}

/**
* Run codemod on a script file or the script part of a .vue file
* @param {string} file the path to the file to transform
* @param {Codemod} codemod the codemod module to run
* @param {object} options additional options for the codemod
*/
transformScript (file, codemod, options) {
this._injectFileMiddleware(files => {
files[file] = runCodemod(
codemod,
{ path: this.resolve(file), source: files[file] },
options
)
})
}

/**
* Add import statements to a file.
*/
Expand Down
2 changes: 1 addition & 1 deletion packages/@vue/cli/package.json
Expand Up @@ -56,7 +56,7 @@
"shortid": "^2.2.11",
"slash": "^3.0.0",
"validate-npm-package-name": "^3.0.0",
"vue-jscodeshift-adapter": "2.0.2",
"vue-jscodeshift-adapter": "^2.0.2",
"yaml-front-matter": "^3.4.1"
},
"engines": {
Expand Down

0 comments on commit 5460ca4

Please sign in to comment.