Skip to content

Commit

Permalink
feat: add makeJSOnlyValue to generator API (#3568)
Browse files Browse the repository at this point in the history
Provides convenience method for passing JS into config files.
Closes issue #3535.
  • Loading branch information
steveworkman authored and haoqunjiang committed Apr 9, 2019
1 parent cb11397 commit f69339e
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
8 changes: 8 additions & 0 deletions docs/dev-guide/generator-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,14 @@ Add a message to be printed when the generator exits (after any other standard m
- **Usage**:
Convenience method for generating a JS config file from JSON

## makeJSOnlyValue

- **Arguments**
- `{any} str` - JS expression as a string

- **Usage**:
Turns a string expression into executable JS for .js config files

## injectImports

- **Arguments**
Expand Down
20 changes: 20 additions & 0 deletions packages/@vue/cli/__tests__/Generator.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -656,3 +656,23 @@ test('extract config files', async () => {
expect(fs.readFileSync('/jest.config.js', 'utf-8')).toMatch(js(configs.jest))
expect(fs.readFileSync('/.browserslistrc', 'utf-8')).toMatch('> 1%\nnot <= IE8')
})

test('generate a JS-Only value from a string', async () => {
const jsAsString = 'true ? "alice" : "bob"'

const generator = new Generator('/', { plugins: [
{
id: 'test',
apply: api => {
api.extendPackage({
testScript: api.makeJSOnlyValue(jsAsString)
})
}
}
] })

await generator.generate({})

expect(generator.pkg).toHaveProperty('testScript')
expect(typeof generator.pkg.testScript).toBe('function')
})
10 changes: 10 additions & 0 deletions packages/@vue/cli/lib/GeneratorAPI.js
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,16 @@ class GeneratorAPI {
return `module.exports = ${stringifyJS(value, null, 2)}`
}

/**
* Turns a string expression into executable JS for JS configs.
* @param {*} str JS expression as a string
*/
makeJSOnlyValue (str) {
const fn = () => {}
fn.__expression = str
return fn
}

/**
* Add import statements to a file.
*/
Expand Down

0 comments on commit f69339e

Please sign in to comment.