1
1
import deIndent from 'de-indent' ;
2
2
import htmlMinifier from 'html-minifier' ;
3
+ import { compile as compileTemplate } from 'vue-template-compiler' ;
3
4
import parse5 from 'parse5' ;
4
5
import validateTemplate from 'vue-template-validator' ;
5
6
import { relative } from 'path' ;
@@ -38,6 +39,25 @@ function padContent(content) {
38
39
. join ( '\n' ) ;
39
40
}
40
41
42
+ /**
43
+ * Only support for es5 modules
44
+ *
45
+ * @param script
46
+ * @param render
47
+ * @returns {string }
48
+ */
49
+ function injectRender ( script , render ) {
50
+ const matches = / ( e x p o r t d e f a u l t [ ^ { ] * \{ ) / g. exec ( script ) ;
51
+ if ( matches ) {
52
+ function toFunction ( code ) {
53
+ return `function(){${ code } })` ;
54
+ }
55
+ return script . split ( matches [ 1 ] )
56
+ . join ( `${ matches [ 1 ] } render: ${ toFunction ( render . render ) } , staticRenderFns: [${ render . staticRenderFns . map ( toFunction ) . join ( ',' ) } ]` ) ;
57
+ }
58
+ throw new Error ( '[rollup-plugin-vue] could not find place to inject template in script.' ) ;
59
+ }
60
+
41
61
/**
42
62
* Only support for es5 modules
43
63
*
@@ -78,15 +98,21 @@ function processTemplate(node, filePath, content) {
78
98
* @param {string } content
79
99
* @param {string } template
80
100
*/
81
- function processScript ( node , filePath , content , template ) {
101
+ function processScript ( node , filePath , content , { template, render } ) {
82
102
const lang = checkLang ( node ) || 'js' ;
83
103
let script = parse5 . serialize ( node ) ;
84
104
// pad the script to ensure correct line number for syntax errors
85
105
const location = content . indexOf ( script ) ;
86
106
const before = padContent ( content . slice ( 0 , location ) ) ;
87
107
script = before + script ;
88
- script = injectTemplate ( script , template , lang ) ;
108
+ if ( template ) {
109
+ script = injectTemplate ( script , template , lang ) ;
110
+ } else if ( render ) {
111
+ script = injectRender ( script , render , lang ) ;
112
+ }
89
113
script = deIndent ( script ) ;
114
+
115
+ console . log ( script )
90
116
return script ;
91
117
}
92
118
@@ -108,10 +134,11 @@ export default function vueTransform(code, filePath) {
108
134
109
135
// 4. Process template
110
136
const template = processTemplate ( nodes . template , filePath , code ) ;
137
+ const render = compileTemplate ( template ) ;
111
138
112
139
// 5. Process script & style
113
140
return {
114
- js : processScript ( nodes . script , filePath , code , template ) ,
141
+ js : processScript ( nodes . script , filePath , code , { render } ) ,
115
142
css : nodes . style && {
116
143
content : parse5 . serialize ( nodes . style ) ,
117
144
lang : checkLang ( nodes . style ) ,
0 commit comments