0
# JavaScript Transpilers
1
2
Built-in compilation support for modern JavaScript dialects and preprocessors including CoffeeScript, ES6+ via Babel, TypeScript, JSX, and LESS CSS preprocessing. All transpilers are self-contained with no external dependencies.
3
4
## Capabilities
5
6
### CoffeeScript Compilation
7
8
Compiles CoffeeScript source code to JavaScript using the built-in CoffeeScript compiler. Supports all standard CoffeeScript language features including classes, comprehensions, and destructuring.
9
10
```python { .api }
11
def coffee_compile(source):
12
"""
13
Compiles the given source from CoffeeScript to JavaScript.
14
15
Parameters:
16
- source: str - CoffeeScript source code
17
18
Returns:
19
str - Compiled JavaScript code
20
21
Raises:
22
JSRuntimeError: When CoffeeScript compilation fails
23
"""
24
```
25
26
Usage example:
27
28
```python
29
import dukpy
30
31
coffee_code = '''
32
square = (x) -> x * x
33
numbers = [1, 2, 3, 4, 5]
34
squares = (square num for num in numbers)
35
console.log squares
36
'''
37
38
js_code = dukpy.coffee_compile(coffee_code)
39
print(js_code)
40
```
41
42
### ES6+ Babel Compilation
43
44
Compiles modern JavaScript (ES6+) to ES5 for broader browser compatibility using BabelJS. Supports extensive configuration through Babel options and plugins.
45
46
```python { .api }
47
def babel_compile(source, **kwargs):
48
"""
49
Compiles the given source from ES6+ to ES5 using BabelJS.
50
51
Parameters:
52
- source: str - ES6+ JavaScript source code
53
- **kwargs: Babel compilation options
54
- presets: list - Babel presets (defaults to ["es2015"])
55
- plugins: list - Babel plugins
56
- filename: str - Source filename for debugging
57
- Other Babel options as documented at http://babeljs.io/docs/usage/options/
58
59
Returns:
60
dict - Compilation result with keys:
61
- 'code': str - Compiled JavaScript code
62
- 'map': dict - Source map information
63
64
Raises:
65
JSRuntimeError: When Babel compilation fails
66
"""
67
```
68
69
Usage example:
70
71
```python
72
import dukpy
73
74
# ES6 class compilation
75
es6_code = '''
76
class Point {
77
constructor(x, y) {
78
this.x = x;
79
this.y = y;
80
}
81
82
toString() {
83
return `(${this.x}, ${this.y})`;
84
}
85
86
static distance(a, b) {
87
const dx = a.x - b.x;
88
const dy = a.y - b.y;
89
return Math.sqrt(dx * dx + dy * dy);
90
}
91
}
92
'''
93
94
result = dukpy.babel_compile(es6_code)
95
print(result['code'])
96
97
# Custom Babel options
98
result = dukpy.babel_compile(es6_code, presets=['es2015'], plugins=['transform-runtime'])
99
print(result['code'])
100
```
101
102
### JSX Compilation
103
104
Compiles JSX syntax to React-compatible JavaScript code using Babel with React presets. Automatically configures Babel for JSX transformation.
105
106
```python { .api }
107
def jsx_compile(source, **kwargs):
108
"""
109
Compiles JSX to React-compatible JavaScript.
110
111
Parameters:
112
- source: str - JSX source code
113
- **kwargs: Babel compilation options (presets automatically set to ['es2015', 'react'])
114
- plugins: list - Additional Babel plugins
115
- filename: str - Source filename for debugging
116
- Other Babel options
117
118
Returns:
119
str - Compiled JavaScript code (code portion only)
120
121
Raises:
122
JSRuntimeError: When JSX compilation fails
123
"""
124
```
125
126
Usage example:
127
128
```python
129
import dukpy
130
131
jsx_code = '''
132
const Greeting = ({ name, age }) => {
133
return (
134
<div className="greeting">
135
<h1>Hello, {name}!</h1>
136
<p>You are {age} years old.</p>
137
<button onClick={() => alert(`Hi ${name}!`)}>
138
Click me
139
</button>
140
</div>
141
);
142
};
143
144
const App = () => (
145
<div>
146
<Greeting name="Alice" age={30} />
147
<Greeting name="Bob" age={25} />
148
</div>
149
);
150
'''
151
152
js_code = dukpy.jsx_compile(jsx_code)
153
print(js_code)
154
```
155
156
### TypeScript Compilation
157
158
Compiles TypeScript source code to ES5 JavaScript using TypeScript Services. Uses fixed compilation options optimized for SystemJS module format and ES5 target.
159
160
```python { .api }
161
def typescript_compile(source):
162
"""
163
Compiles the given source from TypeScript to ES5 using TypescriptServices.js.
164
165
Parameters:
166
- source: str - TypeScript source code
167
168
Returns:
169
str - Compiled JavaScript code
170
171
Note: Uses fixed compiler options:
172
- module: SystemJS (requires SystemJS runtime for import statements)
173
- target: ES5
174
- newLine: LF
175
176
Raises:
177
JSRuntimeError: When TypeScript compilation fails
178
"""
179
```
180
181
Usage example:
182
183
```python
184
import dukpy
185
186
typescript_code = '''
187
interface User {
188
name: string;
189
age: number;
190
email?: string;
191
}
192
193
class UserManager {
194
private users: User[] = [];
195
196
addUser(user: User): void {
197
this.users.push(user);
198
}
199
200
findUser(name: string): User | undefined {
201
return this.users.find(u => u.name === name);
202
}
203
204
getUserCount(): number {
205
return this.users.length;
206
}
207
}
208
209
const manager = new UserManager();
210
manager.addUser({ name: "Alice", age: 30 });
211
'''
212
213
js_code = dukpy.typescript_compile(typescript_code)
214
print(js_code)
215
```
216
217
### LESS CSS Compilation
218
219
Compiles LESS stylesheets to CSS using the Node.js-compatible LESS compiler. Supports LESS language features including variables, mixins, nesting, and imports.
220
221
```python { .api }
222
def less_compile(source, options=None):
223
"""
224
Compiles the given source from LESS to CSS.
225
226
Parameters:
227
- source: str - LESS source code
228
- options: dict, optional - LESS compiler options
229
- paths: list - Include paths for @import resolution
230
- Other LESS compiler options
231
232
Returns:
233
str - Compiled CSS code
234
235
Raises:
236
LessCompilerError: When LESS compilation fails
237
RuntimeError: When compilation results are unavailable
238
"""
239
```
240
241
Usage example:
242
243
```python
244
import dukpy
245
246
less_code = '''
247
@primary-color: #007bff;
248
@secondary-color: #6c757d;
249
@border-radius: 4px;
250
251
.button {
252
background-color: @primary-color;
253
border: 1px solid darken(@primary-color, 10%);
254
border-radius: @border-radius;
255
color: white;
256
padding: 8px 16px;
257
258
&:hover {
259
background-color: darken(@primary-color, 5%);
260
}
261
262
&.secondary {
263
background-color: @secondary-color;
264
border-color: darken(@secondary-color, 10%);
265
}
266
}
267
268
.card {
269
border: 1px solid #dee2e6;
270
border-radius: @border-radius;
271
272
.header {
273
background-color: #f8f9fa;
274
padding: 12px 16px;
275
border-bottom: 1px solid #dee2e6;
276
}
277
278
.body {
279
padding: 16px;
280
}
281
}
282
'''
283
284
css_code = dukpy.less_compile(less_code)
285
print(css_code)
286
287
# With custom options
288
css_code = dukpy.less_compile(less_code, options={
289
'paths': ['./styles', './node_modules'],
290
})
291
```
292
293
## Error Handling
294
295
```python { .api }
296
class LessCompilerError(Exception):
297
"""
298
Exception raised when LESS compilation fails.
299
Contains details about LESS syntax errors, import resolution failures,
300
and other compilation issues.
301
"""
302
```
303
304
Error handling example:
305
306
```python
307
import dukpy
308
309
try:
310
# Invalid LESS syntax
311
css = dukpy.less_compile(".invalid { color: ; }")
312
except dukpy.LessCompilerError as e:
313
print(f"LESS compilation error: {e}")
314
315
try:
316
# Missing import
317
css = dukpy.less_compile('@import "nonexistent.less";')
318
except dukpy.LessCompilerError as e:
319
print(f"LESS compilation error: {e}")
320
```
321
322
## Integration Notes
323
324
### Browser Compatibility
325
326
- **BabelJS**: Compiled ES5 code requires babel-polyfill for full ES6+ feature support
327
- **TypeScript**: Compiled code uses SystemJS modules and requires SystemJS runtime
328
- **JSX**: Compiled code requires React runtime library
329
330
### Asset Pipeline Integration
331
332
All transpilers integrate with WebAssets for automated compilation in web applications. See [WebAssets](./webassets.md) for filter configuration and usage.