forked from coldemo/gallery.code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbabel-worker.js
More file actions
62 lines (60 loc) · 1.59 KB
/
babel-worker.js
File metadata and controls
62 lines (60 loc) · 1.59 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
/* global Babel, importScripts */
// importScripts('https://unpkg.com/@babel/standalone');
// importScripts('https://unpkg.com/@babel/[email protected]/babel.js');
importScripts('./babel.min.js');
let Queue = {
skipMiddle: true,
tasks: [],
async exec({ code, file }) {
try {
let plugins = [];
let hasJsx = file && ['.jsx', '.tsx'].some(ext => file.endsWith(ext));
let hasTs = file && ['.ts', '.tsx'].some(ext => file.endsWith(ext));
if (hasJsx) {
let isVueJsx = /render\s*\(\s*h\s*\)\s*\{/.test(code);
if (isVueJsx) {
plugins.push('syntax-jsx', 'transform-vue-jsx');
} else {
plugins.push('transform-react-jsx');
}
}
if (hasTs) {
if (hasJsx) {
plugins.push(['transform-typescript', { isTSX: true }]);
} else {
plugins.push('transform-typescript');
}
}
if (plugins.length) {
/* cpu-intensive start */
let res = Babel.transform(code, { plugins });
/* cpu-intensive end */
code = res.code;
}
postMessage({ data: code });
} catch (err) {
// postMessage({ error: err ? err.stack : String(err) })
postMessage({ error: err });
}
},
push(task) {
if (this.skipMiddle) {
if (this.tasks.length >= 2) {
this.tasks.length = 1;
}
}
this.tasks.push(task);
this.tick();
},
async tick() {
if (this.tasks.length === 1) {
await this.exec(this.tasks[0]);
this.tasks.shift();
this.tick();
}
},
};
onmessage = e => {
let code = e.data;
Queue.push(code);
};