1
1
class Ctx {
2
2
constructor ( ) {
3
3
this . _temp = '' ;
4
- this . _parentTemp = `"use strict";return @temp;` ;
4
+ this . _parentTemp = `"use strict";\nreturn @temp;` ;
5
5
this . _com = null ;
6
6
if ( ! ( Object . prototype . hasOwnProperty . call ( window , 'Babel' ) && typeof window . Babel === 'object' ) ) {
7
7
throw new Error ( `string-to-react-component package needs @babel/standalone for working correctly.
8
8
you should load @babel/standalone in the browser.` ) ;
9
9
}
10
10
this . _b = window . Babel ;
11
- this . _babelpresets = [ 'react' ] ;
12
11
}
13
- _transpile ( ) {
14
- return this . _b . transform ( this . _temp , {
15
- presets : this . _babelpresets ,
16
- } ) . code ;
12
+ _checkBabelOptions ( babelOptions ) {
13
+ if ( Object . prototype . toString . call ( babelOptions ) !== '[object Object]' ) {
14
+ throw new Error ( `babelOptions prop of string-to-react-component element should be an object.` ) ;
15
+ }
16
+ if ( Object . prototype . hasOwnProperty . call ( babelOptions , 'presets' ) === false ) {
17
+ babelOptions . presets = [ 'react' ] ;
18
+ } else {
19
+ //check if babelOptions.presets is not type of Array
20
+ if ( ! ( typeof babelOptions . presets === 'object' && babelOptions . presets . constructor == Array ) ) {
21
+ throw new Error ( `string-to-react-component Error : presets property of babelOptions prop should be an array` ) ;
22
+ }
23
+ if ( babelOptions . presets . indexOf ( 'react' ) === - 1 ) {
24
+ babelOptions . presets . push ( 'react' ) ;
25
+ }
26
+ }
27
+ }
28
+ _transpile ( babelOptions ) {
29
+ // make sure react presets is registered in babelOptions
30
+ this . _checkBabelOptions ( babelOptions ) ;
31
+ const resultObj = this . _b . transform ( this . _temp , babelOptions ) ;
32
+ const filename = babelOptions . filename ;
33
+ let code = resultObj . code ;
34
+ if ( filename ) {
35
+ code = resultObj . code + `\n//# sourceURL=${ filename } ` ;
36
+ }
37
+ return code ;
17
38
}
18
- _generateCom ( ) {
19
- this . _com = Function ( this . _parentTemp . replace ( '@temp' , this . _transpile ( ) ) ) ( ) ;
39
+ _generateCom ( babelOptions ) {
40
+ this . _com = Function ( this . _parentTemp . replace ( '@temp' , this . _transpile ( babelOptions ) ) ) ( ) ;
20
41
this . _validateCodeInsideTheTemp ( ) ;
21
42
}
22
43
_validateCodeInsideTheTemp ( ) {
@@ -32,11 +53,11 @@ class Ctx {
32
53
throw new Error ( `passed string into string-to-react-component element can not be empty` ) ;
33
54
}
34
55
}
35
- updateTemplate ( template ) {
56
+ updateTemplate ( template , babelOptions ) {
36
57
this . _validateTemplate ( template ) ;
37
58
if ( template !== this . _temp ) {
38
59
this . _temp = template ;
39
- this . _generateCom ( ) ;
60
+ this . _generateCom ( babelOptions ) ;
40
61
}
41
62
return this ;
42
63
}
0 commit comments