-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtransform-script.js
87 lines (76 loc) · 2.23 KB
/
transform-script.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
const babel = require('@babel/core');
function transformToAst(code) {
const { ast } = babel.transformSync(code, {
ast: true,
});
return ast;
}
function transformFromAst(ast) {
const { code } = babel.transformFromAst(ast, '', {});
return code;
}
function generateId(mask = 'xxxxxxxxxx', map = '0123456789abcdef') {
const length = map.length;
return mask.replace(/x/g, () => map[Math.floor(Math.random() * length)]);
}
module.exports = ({ script, template, style, emitCss, id: fileName }) => {
let astExtend;
const isJSComponent = fileName.includes('.f7.js');
const id = generateId();
const astExtendFunction = `
{{ASYNC}}function {{COMPONENT_NAME}}(props, ctx) {
}
{{COMPONENT_NAME}}.id = '${id}';
${
style && !emitCss
? `
{{COMPONENT_NAME}}.style = \`${style}\`;
`.trim()
: ''
}
export default {{COMPONENT_NAME}};
`;
const ast = transformToAst(
`${
isJSComponent
? `/** @jsx $jsx */\nimport { $jsx } from 'framework7';\n`
: ''
}${script}`,
);
ast.program.body.forEach((node, index) => {
if (node.type === 'ExportDefaultDeclaration') {
if (
node.declaration &&
(node.declaration.type === 'ArrowFunctionExpression' ||
node.declaration.type === 'FunctionDeclaration' ||
node.declaration.type === 'FunctionExpression')
) {
astExtend = transformToAst(
astExtendFunction
.replace(/{{COMPONENT_NAME}}/g, `f7component${id}`)
.replace(/{{ASYNC}}/g, node.declaration.async ? 'async ' : ''),
);
astExtend.program.body[0].params = node.declaration.params;
astExtend.program.body[0].body = node.declaration.body;
ast.program.body.splice(index, 1, ...astExtend.program.body);
}
}
});
const code = transformFromAst(ast).replace(
'$render',
`function ($$ctx) {
var $ = $$ctx.$$;
var $h = $$ctx.$h;
var $root = $$ctx.$root;
var $f7 = $$ctx.$f7;
var $f7route = $$ctx.$f7route;
var $f7router = $$ctx.$f7router;
var $theme = $$ctx.$theme;
var $update = $$ctx.$update;
var $store = $$ctx.$store;
return $h\`${template}\`
}
`,
);
return code;
};