-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtransform-script.js
77 lines (67 loc) · 1.84 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
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;
}
module.exports = ({ script, template, id, style }) => {
let astExtend;
const astExtendFunction = `
function {{COMPONENT_NAME}}(props, ctx) {
}
{{COMPONENT_NAME}}.id = '${id}';
${
style
? `
{{COMPONENT_NAME}}.style = \`${style}\`;
`.trim()
: ''
}
export default {{COMPONENT_NAME}};
`;
const ast = transformToAst(
`/** @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,
'framework7Component',
),
);
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;
};