Skip to content

Commit 5d002cc

Browse files
authored
fix: do not throw when api.render is called from an anonymous function (#5801)
Fixes #4774
1 parent 865fdd2 commit 5d002cc

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,6 +531,26 @@ test('api: render fs directory', async () => {
531531
expect(fs.readFileSync('/.vscode/config.json', 'utf-8')).toMatch('{}')
532532
})
533533

534+
// #4774
535+
test('api: call render inside an anonymous function', async () => {
536+
const generator = new Generator('/', { plugins: [
537+
{
538+
id: 'test1',
539+
apply: api => {
540+
(() => {
541+
api.render('./template', { m: 2 })
542+
})()
543+
},
544+
options: {
545+
n: 1
546+
}
547+
}
548+
] })
549+
550+
await generator.generate()
551+
expect(fs.readFileSync('/foo.js', 'utf-8')).toMatch('foo(1)')
552+
})
553+
534554
test('api: render object', async () => {
535555
const generator = new Generator('/', { plugins: [
536556
{

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

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -457,7 +457,18 @@ function extractCallDir () {
457457
const obj = {}
458458
Error.captureStackTrace(obj)
459459
const callSite = obj.stack.split('\n')[3]
460-
const fileName = callSite.match(/\s\((.*):\d+:\d+\)$/)[1]
460+
461+
// the regexp for the stack when called inside a named function
462+
const namedStackRegExp = /\s\((.*):\d+:\d+\)$/
463+
// the regexp for the stack when called inside an anonymous
464+
const anonymousStackRegExp = /at (.*):\d+:\d+$/
465+
466+
let matchResult = callSite.match(namedStackRegExp)
467+
if (!matchResult) {
468+
matchResult = callSite.match(anonymousStackRegExp)
469+
}
470+
471+
const fileName = matchResult[1]
461472
return path.dirname(fileName)
462473
}
463474

0 commit comments

Comments
 (0)