codegen.spec.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. import { parse } from 'compiler/parser/index'
  2. import { optimize } from 'compiler/optimizer'
  3. import { generate } from 'compiler/codegen'
  4. import { isObject, extend } from 'shared/util'
  5. import { isReservedTag } from 'web/util/index'
  6. import { baseOptions } from 'web/compiler/options'
  7. function assertCodegen (template, generatedCode, ...args) {
  8. let staticRenderFnCodes = []
  9. let generateOptions = baseOptions
  10. let proc = null
  11. let len = args.length
  12. while (len--) {
  13. const arg = args[len]
  14. if (Array.isArray(arg)) {
  15. staticRenderFnCodes = arg
  16. } else if (isObject(arg)) {
  17. generateOptions = arg
  18. } else if (typeof arg === 'function') {
  19. proc = arg
  20. }
  21. }
  22. const ast = parse(template, baseOptions)
  23. optimize(ast, baseOptions)
  24. proc && proc(ast)
  25. const res = generate(ast, generateOptions)
  26. expect(res.render).toBe(generatedCode)
  27. expect(res.staticRenderFns).toEqual(staticRenderFnCodes)
  28. }
  29. /* eslint-disable quotes */
  30. describe('codegen', () => {
  31. it('generate directive', () => {
  32. assertCodegen(
  33. '<p v-custom1:arg1.modifier="value1" v-custom2></p>',
  34. `with(this){return _c('p',{directives:[{name:"custom1",rawName:"v-custom1:arg1.modifier",value:(value1),expression:"value1",arg:"arg1",modifiers:{"modifier":true}},{name:"custom2",rawName:"v-custom2"}]})}`
  35. )
  36. })
  37. it('generate filters', () => {
  38. assertCodegen(
  39. '<div :id="a | b | c">{{ d | e | f }}</div>',
  40. `with(this){return _c('div',{attrs:{"id":_f("c")(_f("b")(a))}},[_v(_s(_f("f")(_f("e")(d))))])}`
  41. )
  42. })
  43. it('generate v-for directive', () => {
  44. assertCodegen(
  45. '<div><li v-for="item in items" :key="item.uid"></li></div>',
  46. `with(this){return _c('div',_l((items),function(item){return _c('li',{key:item.uid})}))}`
  47. )
  48. // iterator syntax
  49. assertCodegen(
  50. '<div><li v-for="(item, i) in items"></li></div>',
  51. `with(this){return _c('div',_l((items),function(item,i){return _c('li')}))}`
  52. )
  53. assertCodegen(
  54. '<div><li v-for="(item, key, index) in items"></li></div>',
  55. `with(this){return _c('div',_l((items),function(item,key,index){return _c('li')}))}`
  56. )
  57. // destructuring
  58. assertCodegen(
  59. '<div><li v-for="{ a, b } in items"></li></div>',
  60. `with(this){return _c('div',_l((items),function({ a, b }){return _c('li')}))}`
  61. )
  62. assertCodegen(
  63. '<div><li v-for="({ a, b }, key, index) in items"></li></div>',
  64. `with(this){return _c('div',_l((items),function({ a, b },key,index){return _c('li')}))}`
  65. )
  66. // v-for with extra element
  67. assertCodegen(
  68. '<div><p></p><li v-for="item in items"></li></div>',
  69. `with(this){return _c('div',[_c('p'),_l((items),function(item){return _c('li')})],2)}`
  70. )
  71. })
  72. it('generate v-if directive', () => {
  73. assertCodegen(
  74. '<p v-if="show">hello</p>',
  75. `with(this){return (show)?_c('p',[_v("hello")]):_e()}`
  76. )
  77. })
  78. it('generate v-else directive', () => {
  79. assertCodegen(
  80. '<div><p v-if="show">hello</p><p v-else>world</p></div>',
  81. `with(this){return _c('div',[(show)?_c('p',[_v("hello")]):_c('p',[_v("world")])])}`
  82. )
  83. })
  84. it('generate v-else-if directive', () => {
  85. assertCodegen(
  86. '<div><p v-if="show">hello</p><p v-else-if="hide">world</p></div>',
  87. `with(this){return _c('div',[(show)?_c('p',[_v("hello")]):(hide)?_c('p',[_v("world")]):_e()])}`
  88. )
  89. })
  90. it('generate v-else-if with v-else directive', () => {
  91. assertCodegen(
  92. '<div><p v-if="show">hello</p><p v-else-if="hide">world</p><p v-else>bye</p></div>',
  93. `with(this){return _c('div',[(show)?_c('p',[_v("hello")]):(hide)?_c('p',[_v("world")]):_c('p',[_v("bye")])])}`
  94. )
  95. })
  96. it('generate multi v-else-if with v-else directive', () => {
  97. assertCodegen(
  98. '<div><p v-if="show">hello</p><p v-else-if="hide">world</p><p v-else-if="3">elseif</p><p v-else>bye</p></div>',
  99. `with(this){return _c('div',[(show)?_c('p',[_v("hello")]):(hide)?_c('p',[_v("world")]):(3)?_c('p',[_v("elseif")]):_c('p',[_v("bye")])])}`
  100. )
  101. })
  102. it('generate ref', () => {
  103. assertCodegen(
  104. '<p ref="component1"></p>',
  105. `with(this){return _c('p',{ref:"component1"})}`
  106. )
  107. })
  108. it('generate ref on v-for', () => {
  109. assertCodegen(
  110. '<ul><li v-for="item in items" ref="component1"></li></ul>',
  111. `with(this){return _c('ul',_l((items),function(item){return _c('li',{ref:"component1",refInFor:true})}))}`
  112. )
  113. })
  114. it('generate v-bind directive', () => {
  115. assertCodegen(
  116. '<p v-bind="test"></p>',
  117. `with(this){return _c('p',_b({},'p',test,false))}`
  118. )
  119. })
  120. it('generate v-bind with prop directive', () => {
  121. assertCodegen(
  122. '<p v-bind.prop="test"></p>',
  123. `with(this){return _c('p',_b({},'p',test,true))}`
  124. )
  125. })
  126. it('generate v-bind directive with sync modifier', () => {
  127. assertCodegen(
  128. '<p v-bind.sync="test"></p>',
  129. `with(this){return _c('p',_b({},'p',test,false,true))}`
  130. )
  131. })
  132. it('generate template tag', () => {
  133. assertCodegen(
  134. '<div><template><p>{{hello}}</p></template></div>',
  135. `with(this){return _c('div',[[_c('p',[_v(_s(hello))])]],2)}`
  136. )
  137. })
  138. it('generate single slot', () => {
  139. assertCodegen(
  140. '<div><slot></slot></div>',
  141. `with(this){return _c('div',[_t("default")],2)}`
  142. )
  143. })
  144. it('generate named slot', () => {
  145. assertCodegen(
  146. '<div><slot name="one"></slot></div>',
  147. `with(this){return _c('div',[_t("one")],2)}`
  148. )
  149. })
  150. it('generate slot fallback content', () => {
  151. assertCodegen(
  152. '<div><slot><div>hi</div></slot></div>',
  153. `with(this){return _c('div',[_t("default",[_c('div',[_v("hi")])])],2)}`
  154. )
  155. })
  156. it('generate slot target', () => {
  157. assertCodegen(
  158. '<p slot="one">hello world</p>',
  159. `with(this){return _c('p',{attrs:{"slot":"one"},slot:"one"},[_v("hello world")])}`
  160. )
  161. })
  162. it('generate scoped slot', () => {
  163. assertCodegen(
  164. '<foo><template slot-scope="bar">{{ bar }}</template></foo>',
  165. `with(this){return _c('foo',{scopedSlots:_u([{key:"default",fn:function(bar){return [_v(_s(bar))]}}])})}`
  166. )
  167. assertCodegen(
  168. '<foo><div slot-scope="bar">{{ bar }}</div></foo>',
  169. `with(this){return _c('foo',{scopedSlots:_u([{key:"default",fn:function(bar){return _c('div',{},[_v(_s(bar))])}}])})}`
  170. )
  171. })
  172. it('generate named scoped slot', () => {
  173. assertCodegen(
  174. '<foo><template slot="foo" slot-scope="bar">{{ bar }}</template></foo>',
  175. `with(this){return _c('foo',{scopedSlots:_u([{key:"foo",fn:function(bar){return [_v(_s(bar))]}}])})}`
  176. )
  177. assertCodegen(
  178. '<foo><div slot="foo" slot-scope="bar">{{ bar }}</div></foo>',
  179. `with(this){return _c('foo',{scopedSlots:_u([{key:"foo",fn:function(bar){return _c('div',{},[_v(_s(bar))])}}])})}`
  180. )
  181. })
  182. it('generate class binding', () => {
  183. // static
  184. assertCodegen(
  185. '<p class="class1">hello world</p>',
  186. `with(this){return _c('p',{staticClass:"class1"},[_v("hello world")])}`,
  187. )
  188. // dynamic
  189. assertCodegen(
  190. '<p :class="class1">hello world</p>',
  191. `with(this){return _c('p',{class:class1},[_v("hello world")])}`
  192. )
  193. })
  194. it('generate style binding', () => {
  195. assertCodegen(
  196. '<p :style="error">hello world</p>',
  197. `with(this){return _c('p',{style:(error)},[_v("hello world")])}`
  198. )
  199. })
  200. it('generate v-show directive', () => {
  201. assertCodegen(
  202. '<p v-show="shown">hello world</p>',
  203. `with(this){return _c('p',{directives:[{name:"show",rawName:"v-show",value:(shown),expression:"shown"}]},[_v("hello world")])}`
  204. )
  205. })
  206. it('generate DOM props with v-bind directive', () => {
  207. // input + value
  208. assertCodegen(
  209. '<input :value="msg">',
  210. `with(this){return _c('input',{domProps:{"value":msg}})}`
  211. )
  212. // non input
  213. assertCodegen(
  214. '<p :value="msg"/>',
  215. `with(this){return _c('p',{attrs:{"value":msg}})}`
  216. )
  217. })
  218. it('generate attrs with v-bind directive', () => {
  219. assertCodegen(
  220. '<input :name="field1">',
  221. `with(this){return _c('input',{attrs:{"name":field1}})}`
  222. )
  223. })
  224. it('generate static attrs', () => {
  225. assertCodegen(
  226. '<input name="field1">',
  227. `with(this){return _c('input',{attrs:{"name":"field1"}})}`
  228. )
  229. })
  230. it('generate events with v-on directive', () => {
  231. assertCodegen(
  232. '<input @input="onInput">',
  233. `with(this){return _c('input',{on:{"input":onInput}})}`
  234. )
  235. })
  236. it('generate events with keycode', () => {
  237. assertCodegen(
  238. '<input @input.enter="onInput">',
  239. `with(this){return _c('input',{on:{"input":function($event){if(!('button' in $event)&&_k($event.keyCode,"enter",13,$event.key))return null;onInput($event)}}})}`
  240. )
  241. // multiple keycodes (delete)
  242. assertCodegen(
  243. '<input @input.delete="onInput">',
  244. `with(this){return _c('input',{on:{"input":function($event){if(!('button' in $event)&&_k($event.keyCode,"delete",[8,46],$event.key))return null;onInput($event)}}})}`
  245. )
  246. // multiple keycodes (chained)
  247. assertCodegen(
  248. '<input @keydown.enter.delete="onInput">',
  249. `with(this){return _c('input',{on:{"keydown":function($event){if(!('button' in $event)&&_k($event.keyCode,"enter",13,$event.key)&&_k($event.keyCode,"delete",[8,46],$event.key))return null;onInput($event)}}})}`
  250. )
  251. // number keycode
  252. assertCodegen(
  253. '<input @input.13="onInput">',
  254. `with(this){return _c('input',{on:{"input":function($event){if(!('button' in $event)&&$event.keyCode!==13)return null;onInput($event)}}})}`
  255. )
  256. // custom keycode
  257. assertCodegen(
  258. '<input @input.custom="onInput">',
  259. `with(this){return _c('input',{on:{"input":function($event){if(!('button' in $event)&&_k($event.keyCode,"custom",undefined,$event.key))return null;onInput($event)}}})}`
  260. )
  261. })
  262. it('generate events with generic modifiers', () => {
  263. assertCodegen(
  264. '<input @input.stop="onInput">',
  265. `with(this){return _c('input',{on:{"input":function($event){$event.stopPropagation();onInput($event)}}})}`
  266. )
  267. assertCodegen(
  268. '<input @input.prevent="onInput">',
  269. `with(this){return _c('input',{on:{"input":function($event){$event.preventDefault();onInput($event)}}})}`
  270. )
  271. assertCodegen(
  272. '<input @input.self="onInput">',
  273. `with(this){return _c('input',{on:{"input":function($event){if($event.target !== $event.currentTarget)return null;onInput($event)}}})}`
  274. )
  275. })
  276. // GitHub Issues #5146
  277. it('generate events with generic modifiers and keycode correct order', () => {
  278. assertCodegen(
  279. '<input @keydown.enter.prevent="onInput">',
  280. `with(this){return _c('input',{on:{"keydown":function($event){if(!('button' in $event)&&_k($event.keyCode,"enter",13,$event.key))return null;$event.preventDefault();onInput($event)}}})}`
  281. )
  282. assertCodegen(
  283. '<input @keydown.enter.stop="onInput">',
  284. `with(this){return _c('input',{on:{"keydown":function($event){if(!('button' in $event)&&_k($event.keyCode,"enter",13,$event.key))return null;$event.stopPropagation();onInput($event)}}})}`
  285. )
  286. })
  287. it('generate events with mouse event modifiers', () => {
  288. assertCodegen(
  289. '<input @click.ctrl="onClick">',
  290. `with(this){return _c('input',{on:{"click":function($event){if(!$event.ctrlKey)return null;onClick($event)}}})}`
  291. )
  292. assertCodegen(
  293. '<input @click.shift="onClick">',
  294. `with(this){return _c('input',{on:{"click":function($event){if(!$event.shiftKey)return null;onClick($event)}}})}`
  295. )
  296. assertCodegen(
  297. '<input @click.alt="onClick">',
  298. `with(this){return _c('input',{on:{"click":function($event){if(!$event.altKey)return null;onClick($event)}}})}`
  299. )
  300. assertCodegen(
  301. '<input @click.meta="onClick">',
  302. `with(this){return _c('input',{on:{"click":function($event){if(!$event.metaKey)return null;onClick($event)}}})}`
  303. )
  304. assertCodegen(
  305. '<input @click.exact="onClick">',
  306. `with(this){return _c('input',{on:{"click":function($event){if($event.ctrlKey||$event.shiftKey||$event.altKey||$event.metaKey)return null;onClick($event)}}})}`
  307. )
  308. assertCodegen(
  309. '<input @click.ctrl.exact="onClick">',
  310. `with(this){return _c('input',{on:{"click":function($event){if(!$event.ctrlKey)return null;if($event.shiftKey||$event.altKey||$event.metaKey)return null;onClick($event)}}})}`
  311. )
  312. })
  313. it('generate events with multiple modifiers', () => {
  314. assertCodegen(
  315. '<input @input.stop.prevent.self="onInput">',
  316. `with(this){return _c('input',{on:{"input":function($event){$event.stopPropagation();$event.preventDefault();if($event.target !== $event.currentTarget)return null;onInput($event)}}})}`
  317. )
  318. })
  319. it('generate events with capture modifier', () => {
  320. assertCodegen(
  321. '<input @input.capture="onInput">',
  322. `with(this){return _c('input',{on:{"!input":function($event){onInput($event)}}})}`
  323. )
  324. })
  325. it('generate events with once modifier', () => {
  326. assertCodegen(
  327. '<input @input.once="onInput">',
  328. `with(this){return _c('input',{on:{"~input":function($event){onInput($event)}}})}`
  329. )
  330. })
  331. it('generate events with capture and once modifier', () => {
  332. assertCodegen(
  333. '<input @input.capture.once="onInput">',
  334. `with(this){return _c('input',{on:{"~!input":function($event){onInput($event)}}})}`
  335. )
  336. })
  337. it('generate events with once and capture modifier', () => {
  338. assertCodegen(
  339. '<input @input.once.capture="onInput">',
  340. `with(this){return _c('input',{on:{"~!input":function($event){onInput($event)}}})}`
  341. )
  342. })
  343. it('generate events with inline statement', () => {
  344. assertCodegen(
  345. '<input @input="current++">',
  346. `with(this){return _c('input',{on:{"input":function($event){current++}}})}`
  347. )
  348. })
  349. it('generate events with inline function expression', () => {
  350. // normal function
  351. assertCodegen(
  352. '<input @input="function () { current++ }">',
  353. `with(this){return _c('input',{on:{"input":function () { current++ }}})}`
  354. )
  355. // arrow with no args
  356. assertCodegen(
  357. '<input @input="()=>current++">',
  358. `with(this){return _c('input',{on:{"input":()=>current++}})}`
  359. )
  360. // arrow with parens, single arg
  361. assertCodegen(
  362. '<input @input="(e) => current++">',
  363. `with(this){return _c('input',{on:{"input":(e) => current++}})}`
  364. )
  365. // arrow with parens, multi args
  366. assertCodegen(
  367. '<input @input="(a, b, c) => current++">',
  368. `with(this){return _c('input',{on:{"input":(a, b, c) => current++}})}`
  369. )
  370. // arrow with destructuring
  371. assertCodegen(
  372. '<input @input="({ a, b }) => current++">',
  373. `with(this){return _c('input',{on:{"input":({ a, b }) => current++}})}`
  374. )
  375. // arrow single arg no parens
  376. assertCodegen(
  377. '<input @input="e=>current++">',
  378. `with(this){return _c('input',{on:{"input":e=>current++}})}`
  379. )
  380. // with modifiers
  381. assertCodegen(
  382. `<input @keyup.enter="e=>current++">`,
  383. `with(this){return _c('input',{on:{"keyup":function($event){if(!('button' in $event)&&_k($event.keyCode,"enter",13,$event.key))return null;(e=>current++)($event)}}})}`
  384. )
  385. })
  386. // #3893
  387. it('should not treat handler with unexpected whitespace as inline statement', () => {
  388. assertCodegen(
  389. '<input @input=" onInput ">',
  390. `with(this){return _c('input',{on:{"input": onInput }})}`
  391. )
  392. })
  393. it('generate unhandled events', () => {
  394. assertCodegen(
  395. '<input @input="current++">',
  396. `with(this){return _c('input',{on:{"input":function(){}}})}`,
  397. ast => {
  398. ast.events.input = undefined
  399. }
  400. )
  401. })
  402. it('generate multiple event handlers', () => {
  403. assertCodegen(
  404. '<input @input="current++" @input.stop="onInput">',
  405. `with(this){return _c('input',{on:{"input":[function($event){current++},function($event){$event.stopPropagation();onInput($event)}]}})}`
  406. )
  407. })
  408. it('generate component', () => {
  409. assertCodegen(
  410. '<my-component name="mycomponent1" :msg="msg" @notify="onNotify"><div>hi</div></my-component>',
  411. `with(this){return _c('my-component',{attrs:{"name":"mycomponent1","msg":msg},on:{"notify":onNotify}},[_c('div',[_v("hi")])])}`
  412. )
  413. })
  414. it('generate svg component with children', () => {
  415. assertCodegen(
  416. '<svg><my-comp><circle :r="10"></circle></my-comp></svg>',
  417. `with(this){return _c('svg',[_c('my-comp',[_c('circle',{attrs:{"r":10}})])],1)}`
  418. )
  419. })
  420. it('generate is attribute', () => {
  421. assertCodegen(
  422. '<div is="component1"></div>',
  423. `with(this){return _c("component1",{tag:"div"})}`
  424. )
  425. assertCodegen(
  426. '<div :is="component1"></div>',
  427. `with(this){return _c(component1,{tag:"div"})}`
  428. )
  429. })
  430. it('generate component with inline-template', () => {
  431. // have "inline-template'"
  432. assertCodegen(
  433. '<my-component inline-template><p><span>hello world</span></p></my-component>',
  434. `with(this){return _c('my-component',{inlineTemplate:{render:function(){with(this){return _m(0)}},staticRenderFns:[function(){with(this){return _c('p',[_c('span',[_v("hello world")])])}}]}})}`
  435. )
  436. // "have inline-template attrs, but not having exactly one child element
  437. assertCodegen(
  438. '<my-component inline-template><hr><hr></my-component>',
  439. `with(this){return _c('my-component',{inlineTemplate:{render:function(){with(this){return _c('hr')}},staticRenderFns:[]}})}`
  440. )
  441. try {
  442. assertCodegen(
  443. '<my-component inline-template></my-component>',
  444. ''
  445. )
  446. } catch (e) {}
  447. expect('Inline-template components must have exactly one child element.').toHaveBeenWarned()
  448. expect(console.error.calls.count()).toBe(2)
  449. })
  450. it('generate static trees inside v-for', () => {
  451. assertCodegen(
  452. `<div><div v-for="i in 10"><p><span></span></p></div></div>`,
  453. `with(this){return _c('div',_l((10),function(i){return _c('div',[_m(0,true)])}))}`,
  454. [`with(this){return _c('p',[_c('span')])}`]
  455. )
  456. })
  457. it('generate component with v-for', () => {
  458. // normalize type: 2
  459. assertCodegen(
  460. '<div><child></child><template v-for="item in list">{{ item }}</template></div>',
  461. `with(this){return _c('div',[_c('child'),_l((list),function(item){return [_v(_s(item))]})],2)}`
  462. )
  463. })
  464. it('generate component with comment', () => {
  465. const options = extend({
  466. comments: true
  467. }, baseOptions)
  468. const template = '<div><!--comment--></div>'
  469. const generatedCode = `with(this){return _c('div',[_e("comment")])}`
  470. const ast = parse(template, options)
  471. optimize(ast, options)
  472. const res = generate(ast, options)
  473. expect(res.render).toBe(generatedCode)
  474. })
  475. // #6150
  476. it('generate comments with special characters', () => {
  477. const options = extend({
  478. comments: true
  479. }, baseOptions)
  480. const template = '<div><!--\n\'comment\'\n--></div>'
  481. const generatedCode = `with(this){return _c('div',[_e("\\n'comment'\\n")])}`
  482. const ast = parse(template, options)
  483. optimize(ast, options)
  484. const res = generate(ast, options)
  485. expect(res.render).toBe(generatedCode)
  486. })
  487. it('not specified ast type', () => {
  488. const res = generate(null, baseOptions)
  489. expect(res.render).toBe(`with(this){return _c("div")}`)
  490. expect(res.staticRenderFns).toEqual([])
  491. })
  492. it('not specified directives option', () => {
  493. assertCodegen(
  494. '<p v-if="show">hello world</p>',
  495. `with(this){return (show)?_c('p',[_v("hello world")]):_e()}`,
  496. { isReservedTag }
  497. )
  498. })
  499. })
  500. /* eslint-enable quotes */