Skip to content

Commit d8d051f

Browse files
committed
Merge pull request facebookarchive#16 from andreypopp/es6-strip_types
jsx: add harmony and strip_types options
2 parents 8cfbb35 + f539c6d commit d8d051f

File tree

2 files changed

+28
-8
lines changed

2 files changed

+28
-8
lines changed

react/jsx.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,24 +23,29 @@ def __init__(self):
2323
with open(path, 'rU') as f:
2424
self.context = execjs.compile(f.read())
2525

26-
def transform_string(self, jsx):
26+
def transform_string(self, jsx, harmony=False, strip_types=False):
2727
""" Transform ``jsx`` JSX string into javascript
2828
2929
:param jsx: JSX source code
3030
:type jsx: basestring
31+
:keyword harmony: Transform ES6 code into ES3 (default: False)
32+
:type harmony: bool
33+
:keyword strip_types: Strip type declarations (default: False)
34+
:type harmony: bool
3135
:return: compiled JS code
3236
:rtype: str
3337
"""
38+
opts = {'harmony': harmony, 'stripTypes': strip_types}
3439
try:
35-
result = self.context.call('JSXTransformer.transform', jsx)
36-
js = result['code']
37-
return js
40+
result = self.context.call('JSXTransformer.transform', jsx, opts)
3841
except execjs.ProgramError as e:
3942
raise TransformError(e.message[7:])
43+
js = result['code']
44+
return js
4045

41-
def transform(self, jsx_path, js_path=None):
46+
def transform(self, jsx_path, js_path=None, **kwargs):
4247
with open(jsx_path, 'rU') as i:
43-
js = self.transform_string(i.read())
48+
js = self.transform_string(i.read(), **kwargs)
4449
if js_path:
4550
with open(js_path, 'wb') as o:
4651
o.write(js.encode('utf8'))
@@ -52,5 +57,8 @@ def __init__(self, message):
5257
Exception.__init__(self, message)
5358

5459

55-
def transform(jsx_path, js_path=None):
56-
return JSXTransformer().transform(jsx_path, js_path)
60+
def transform(jsx_path, **opts):
61+
return JSXTransformer().transform(jsx_path, **opts)
62+
63+
def transform_string(jsx, **opts):
64+
return JSXTransformer().transform_string(jsx, **opts)

react/test/jsx.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,15 @@ def test_transform(self):
3333
self.assertRaises(
3434
jsx.TransformError,
3535
lambda: jsx.transform(malformed_path))
36+
37+
def test_transform_string(self):
38+
result = jsx.transform_string('<div />')
39+
self.assertEquals(result, 'React.createElement("div", null)')
40+
41+
def test_transform_string_harmony(self):
42+
result = jsx.transform_string('var {x} = y', harmony=True)
43+
self.assertEquals(result, 'var $__0= y,x=$__0.x')
44+
45+
def test_transform_string_strip_types(self):
46+
result = jsx.transform_string('var x: Number = 1', strip_types=True)
47+
self.assertEquals(result, 'var x = 1')

0 commit comments

Comments
 (0)