-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
87 lines (65 loc) · 2.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"use strict";
(function () {
window.translateSFC = function (source) {
var script = extract(source, "script").content;
var match = script.match(/(name ?:|data ?[:(](.*){|methods ?:|props ?:|computed ?:|components ?:)/im);
var template = extract(source, "template").content;
var result = script.substr(0, match.index) + "template: `" + template + "`," + script.substr(match.index);
appendStyle(parseStyle(source));
return result;
};
function extract(text, tag) {
var firstTagSymbols = "<" + tag;
var start = text.indexOf(firstTagSymbols);
var contentStart = findTagEnd(text, start);
var contentEnd = text.indexOf("</" + tag + ">");
return {
content: start !== -1 ? text.substring(contentStart, contentEnd) : null,
attrs: text.substring(start + firstTagSymbols.length, contentStart - 1)
}
}
function findTagEnd(text, start) {
var i = start;
while (i < text.length && text[i++] !== ">") {}
return i;
}
function parseStyle(text) {
var styleInfo = extract(text, "style");
if (styleInfo.content) {
styleInfo.content = styleInfo.content.replace(/[\n\r]+/g, "").replace(/ {2,20}/g, " ");
}
return styleInfo;
}
function appendStyle(styleInfo) {
if (typeof document === "undefined") return;
var css = styleInfo.content;
var src = findSrc(styleInfo.attrs);
if (!css && !src) return;
var style = document.createElement(src ? "link" : "style");
style.type = "text/css";
if(src) {
style.setAttribute("href", src);
style.setAttribute("rel", "stylesheet");
} else {
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
}
var head = document.head || document.querySelector("head") || document.getElementsByTagName("head")[0];
head.appendChild(style);
}
function findSrc(attrs) {
if (!attrs) return "";
var result = attrs.match(/src="(.*)"/i);
return result ? result[1] : "";
}
})();
if (typeof exports !== 'undefined') {
exports.translate = function () {
return function (load) {
return load.source = translateSFC(load.source);
};
}();
}