Skip to content

Commit

Permalink
wip compile templates
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed Sep 4, 2016
1 parent 7b45ae4 commit 9f5dd9f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
3 changes: 2 additions & 1 deletion package.json
Expand Up @@ -48,6 +48,7 @@
"rollup": "latest",
"rollup-plugin-buble": "^0.13.0",
"rollup-plugin-replace": "latest",
"vue-hot-reload-api": "^1.2.2"
"vue-hot-reload-api": "^1.2.2",
"vue-template-compiler": "^2.0.0-rc.4"
}
}
33 changes: 30 additions & 3 deletions src/vueTransform.js
@@ -1,5 +1,6 @@
import deIndent from 'de-indent';
import htmlMinifier from 'html-minifier';
import { compile as compileTemplate } from 'vue-template-compiler';
import parse5 from 'parse5';
import validateTemplate from 'vue-template-validator';
import { relative } from 'path';
Expand Down Expand Up @@ -38,6 +39,25 @@ function padContent(content) {
.join('\n');
}

/**
* Only support for es5 modules
*
* @param script
* @param render
* @returns {string}
*/
function injectRender(script, render) {
const matches = /(export default[^{]*\{)/g.exec(script);
if (matches) {
function toFunction (code) {
return `function(){${code}})`;
}
return script.split(matches[1])
.join(`${matches[1]} render: ${toFunction(render.render)}, staticRenderFns: [${render.staticRenderFns.map(toFunction).join(',')}]`);
}
throw new Error('[rollup-plugin-vue] could not find place to inject template in script.');
}

/**
* Only support for es5 modules
*
Expand Down Expand Up @@ -78,15 +98,21 @@ function processTemplate(node, filePath, content) {
* @param {string} content
* @param {string} template
*/
function processScript(node, filePath, content, template) {
function processScript(node, filePath, content, {template, render}) {
const lang = checkLang(node) || 'js';
let script = parse5.serialize(node);
// pad the script to ensure correct line number for syntax errors
const location = content.indexOf(script);
const before = padContent(content.slice(0, location));
script = before + script;
script = injectTemplate(script, template, lang);
if (template) {
script = injectTemplate(script, template, lang);
} else if (render) {
script = injectRender(script, render, lang);
}
script = deIndent(script);

console.log(script)
return script;
}

Expand All @@ -108,10 +134,11 @@ export default function vueTransform(code, filePath) {

// 4. Process template
const template = processTemplate(nodes.template, filePath, code);
const render = compileTemplate(template);

// 5. Process script & style
return {
js: processScript(nodes.script, filePath, code, template),
js: processScript(nodes.script, filePath, code, { render }),
css: nodes.style && {
content: parse5.serialize(nodes.style),
lang: checkLang(nodes.style),
Expand Down

0 comments on commit 9f5dd9f

Please sign in to comment.