11class Ctx {
22 constructor() {
33 this._temp = '';
4- this._parentTemp = `"use strict";return @temp;`;
4+ this._parentTemp = `"use strict";\nreturn @temp;`;
55 this._com = null;
66 if (!(Object.prototype.hasOwnProperty.call(window, 'Babel') && typeof window.Babel === 'object')) {
77 throw new Error(`string-to-react-component package needs @babel/standalone for working correctly.
88 you should load @babel/standalone in the browser.`);
99 }
1010 this._b = window.Babel;
11- this._babelpresets = ['react'];
1211 }
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;
1738 }
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 )))();
2041 this._validateCodeInsideTheTemp();
2142 }
2243 _validateCodeInsideTheTemp() {
@@ -32,11 +53,11 @@ class Ctx {
3253 throw new Error(`passed string into string-to-react-component element can not be empty`);
3354 }
3455 }
35- updateTemplate(template) {
56+ updateTemplate(template, babelOptions ) {
3657 this._validateTemplate(template);
3758 if (template !== this._temp) {
3859 this._temp = template;
39- this._generateCom();
60+ this._generateCom(babelOptions );
4061 }
4162 return this;
4263 }
0 commit comments