Skip to content

Commit f69339e

Browse files
steveworkmanhaoqunjiang
authored andcommitted
feat: add makeJSOnlyValue to generator API (#3568)
Provides convenience method for passing JS into config files. Closes issue #3535.
1 parent cb11397 commit f69339e

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

docs/dev-guide/generator-api.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,14 @@ Add a message to be printed when the generator exits (after any other standard m
9797
- **Usage**:
9898
Convenience method for generating a JS config file from JSON
9999

100+
## makeJSOnlyValue
101+
102+
- **Arguments**
103+
- `{any} str` - JS expression as a string
104+
105+
- **Usage**:
106+
Turns a string expression into executable JS for .js config files
107+
100108
## injectImports
101109

102110
- **Arguments**

packages/@vue/cli/__tests__/Generator.spec.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -656,3 +656,23 @@ test('extract config files', async () => {
656656
expect(fs.readFileSync('/jest.config.js', 'utf-8')).toMatch(js(configs.jest))
657657
expect(fs.readFileSync('/.browserslistrc', 'utf-8')).toMatch('> 1%\nnot <= IE8')
658658
})
659+
660+
test('generate a JS-Only value from a string', async () => {
661+
const jsAsString = 'true ? "alice" : "bob"'
662+
663+
const generator = new Generator('/', { plugins: [
664+
{
665+
id: 'test',
666+
apply: api => {
667+
api.extendPackage({
668+
testScript: api.makeJSOnlyValue(jsAsString)
669+
})
670+
}
671+
}
672+
] })
673+
674+
await generator.generate({})
675+
676+
expect(generator.pkg).toHaveProperty('testScript')
677+
expect(typeof generator.pkg.testScript).toBe('function')
678+
})

packages/@vue/cli/lib/GeneratorAPI.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,16 @@ class GeneratorAPI {
240240
return `module.exports = ${stringifyJS(value, null, 2)}`
241241
}
242242

243+
/**
244+
* Turns a string expression into executable JS for JS configs.
245+
* @param {*} str JS expression as a string
246+
*/
247+
makeJSOnlyValue (str) {
248+
const fn = () => {}
249+
fn.__expression = str
250+
return fn
251+
}
252+
243253
/**
244254
* Add import statements to a file.
245255
*/

0 commit comments

Comments
 (0)