forked from ritz078/transform
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbabel.worker.ts
More file actions
77 lines (66 loc) · 1.84 KB
/
babel.worker.ts
File metadata and controls
77 lines (66 loc) · 1.84 KB
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
import { transform } from "@babel/standalone";
import jsonToProptypes from "babel-plugin-json-to-proptypes";
import jsonToMobxTree from "@assets/vendor/babel-plugin-js-to-mobx-state-tree";
import { merge } from "lodash";
import { prettify } from "@utils/prettify";
import { BabelTransforms } from "@constants/babelTransforms";
import objStylesToTemplate from "babel-plugin-object-styles-to-template";
const _self: any = self;
interface Data {
id: string;
payload: {
value: string;
type: BabelTransforms;
settings?: any;
};
}
async function handleJsonToProptypes(value, id) {
let code = JSON.parse(value);
if (typeof code !== "object" || Array.isArray(code)) {
code = merge({}, ...code);
}
const result = transform(`const propTypes = ${JSON.stringify(code)}`, {
plugins: [jsonToProptypes]
}).code;
const prettyCode = await prettify("javascript", result);
_self.postMessage({
id,
payload: prettyCode
});
}
function objectStylesToTemplate(value, id, settings) {
_self.postMessage({
id,
payload: transform(value, {
plugins: [[objStylesToTemplate, settings]]
}).code
});
}
function jsonToMobx(value, id) {
_self.postMessage({
id,
payload: transform(`const myModel = ${value}`, {
plugins: [jsonToMobxTree]
}).code
});
}
_self.onmessage = ({ data: { id, payload } }: { data: Data }) => {
const { value, type, settings } = payload;
try {
if (type === BabelTransforms.JSON_TO_PROPTYPES) {
handleJsonToProptypes(value, id);
} else if (type === BabelTransforms.OBJECT_STYLES_TO_TEMPLATE) {
objectStylesToTemplate(value, id, settings);
} else if (type === BabelTransforms.JSON_TO_MOBX_TREE) {
jsonToMobx(value, id);
}
} catch (e) {
if (IS_DEV) {
console.error(e);
}
_self.postMessage({
id,
err: e.message
});
}
};