Skip to content

Commit

Permalink
fix: do not throw when api.render is called from an anonymous function (
Browse files Browse the repository at this point in the history
#5801)

Fixes #4774
  • Loading branch information
sodatea committed Aug 24, 2020
1 parent 865fdd2 commit 5d002cc
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
20 changes: 20 additions & 0 deletions packages/@vue/cli/__tests__/Generator.spec.js
Expand Up @@ -531,6 +531,26 @@ test('api: render fs directory', async () => {
expect(fs.readFileSync('/.vscode/config.json', 'utf-8')).toMatch('{}')
})

// #4774
test('api: call render inside an anonymous function', async () => {
const generator = new Generator('/', { plugins: [
{
id: 'test1',
apply: api => {
(() => {
api.render('./template', { m: 2 })
})()
},
options: {
n: 1
}
}
] })

await generator.generate()
expect(fs.readFileSync('/foo.js', 'utf-8')).toMatch('foo(1)')
})

test('api: render object', async () => {
const generator = new Generator('/', { plugins: [
{
Expand Down
13 changes: 12 additions & 1 deletion packages/@vue/cli/lib/GeneratorAPI.js
Expand Up @@ -457,7 +457,18 @@ function extractCallDir () {
const obj = {}
Error.captureStackTrace(obj)
const callSite = obj.stack.split('\n')[3]
const fileName = callSite.match(/\s\((.*):\d+:\d+\)$/)[1]

// the regexp for the stack when called inside a named function
const namedStackRegExp = /\s\((.*):\d+:\d+\)$/
// the regexp for the stack when called inside an anonymous
const anonymousStackRegExp = /at (.*):\d+:\d+$/

let matchResult = callSite.match(namedStackRegExp)
if (!matchResult) {
matchResult = callSite.match(anonymousStackRegExp)
}

const fileName = matchResult[1]
return path.dirname(fileName)
}

Expand Down

0 comments on commit 5d002cc

Please sign in to comment.