Skip to content

Commit 02d5330

Browse files
committed
detect and warn against using keywords as property names
1 parent 0d59865 commit 02d5330

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

src/compiler/error-detector.js

+23-4
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@
22

33
import { dirRE } from './parser/index'
44

5+
const keywordRE = new RegExp('\\b' + (
6+
'do,if,in,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
7+
'super,throw,while,yield,delete,export,import,return,switch,typeof,default,' +
8+
'extends,finally,continue,debugger,function,arguments,instanceof'
9+
).split(',').join('\\b|\\b') + '\\b')
10+
511
// detect problematic expressions in a template
612
export function detectErrors (ast: ?ASTNode): Array<string> {
713
const errors: Array<string> = []
@@ -32,9 +38,22 @@ function checkNode (node: ASTNode, errors: Array<string>) {
3238
}
3339

3440
function checkExpression (exp: string, text: string, errors: Array<string>) {
35-
try {
36-
new Function(exp)
37-
} catch (e) {
38-
errors.push(`- invalid expression: ${text}`)
41+
exp = stripToString(exp)
42+
const keywordMatch = exp.match(keywordRE)
43+
if (keywordMatch) {
44+
errors.push(
45+
`- avoid using JavaScript keyword as property name: ` +
46+
`"${keywordMatch[0]}" in expression ${text}`
47+
)
48+
} else {
49+
try {
50+
new Function(exp)
51+
} catch (e) {
52+
errors.push(`- invalid expression: ${text}`)
53+
}
3954
}
4055
}
56+
57+
function stripToString (exp) {
58+
return exp.replace(/^_s\((.*)\)$/, '$1')
59+
}

test/unit/features/options/template.spec.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,11 @@ describe('Options template', () => {
5353

5454
it('warn error in generated function', () => {
5555
new Vue({
56-
template: '<div v-if="!@">{{ a"" }}</div>'
56+
template: '<div v-if="!@"><span>{{ a"" }}</span><span>{{ do + 1 }}</span></div>'
5757
}).$mount()
5858
expect('failed to compile template').toHaveBeenWarned()
5959
expect('invalid expression: v-if="!@"').toHaveBeenWarned()
6060
expect('invalid expression: {{ a"" }}').toHaveBeenWarned()
61+
expect('avoid using JavaScript keyword as property name: "do" in expression {{ do + 1 }}').toHaveBeenWarned()
6162
})
6263
})

0 commit comments

Comments
 (0)