@@ -8,21 +8,27 @@ class Ctx implements IStringToReactApi {
88 return null ;
99 } ;
1010 _getBabel : ( ) => TBabel ;
11+ _getReact : ( ) => TReact ;
1112 constructor ( React : TReact , Babel : TBabel ) {
12- if ( typeof window === 'object' ) {
13- window . React = window . React || React ;
14- }
13+ this . _getReact = ( ) => React ;
1514 if ( ! Babel ) {
1615 throw new Error (
1716 `Package "string-to-react-component" has a missing peer dependency of "@babel/standalone" ( requires ">=7.6.3" )` ,
1817 ) ;
1918 }
2019 this . _getBabel = ( ) => Babel ;
2120 }
21+ _getBabelDefaultOptions ( ) : TransformOptions {
22+ return {
23+ sourceMaps : 'inline' ,
24+ sourceType : 'module' ,
25+ } ;
26+ }
2227 _checkBabelOptions ( babelOptions : TransformOptions ) {
2328 if ( Object . prototype . toString . call ( babelOptions ) !== '[object Object]' ) {
2429 throw new Error ( `babelOptions prop of string-to-react-component element should be an object.` ) ;
2530 }
31+ Object . assign ( babelOptions , this . _getBabelDefaultOptions ( ) , babelOptions ) ;
2632 if ( Object . prototype . hasOwnProperty . call ( babelOptions , 'presets' ) === false ) {
2733 babelOptions . presets = [ 'react' ] ;
2834 } else {
@@ -35,6 +41,37 @@ class Ctx implements IStringToReactApi {
3541 }
3642 }
3743 }
44+ getModule ( code : string ) : Promise < any > {
45+ code = `import React from "react";\nexport default ${ code } ` ;
46+ const op : TransformOptions = {
47+ presets : [ 'react' , [ 'env' , { modules : false } ] ] ,
48+ filename : 'counter.js' ,
49+ sourceMaps : 'inline' ,
50+ sourceType : 'module' ,
51+ } ;
52+ const resultObj = this . _getBabel ( ) . transform ( code , op ) ;
53+ // 1. Define your module code as a string
54+ code = resultObj . code || '' ;
55+ code = code
56+ . replace ( 'export default' , 'export default (React)=>' )
57+ . replace ( 'import React from "react";' , '//import React from "react";' ) ;
58+
59+ // 2. Create a Blob containing the module code
60+ const blob = new Blob ( [ code ] , { type : 'application/javascript' } ) ;
61+ // 3. Create a URL for the Blob
62+ const moduleUrl = URL . createObjectURL ( blob ) ;
63+ // 4. Dynamically import the module using import()
64+ return import ( /* webpackIgnore: true */ moduleUrl )
65+ . then ( ( module ) => {
66+ // Clean up by revoking the object URL
67+ URL . revokeObjectURL ( moduleUrl ) ;
68+
69+ return Promise . resolve ( ( module ?. default || module ) ( this . _getReact ( ) ) ) ;
70+ } )
71+ . catch ( ( error ) => {
72+ console . error ( 'Error loading module:' , error ) ;
73+ } ) ;
74+ }
3875 _transpile ( babelOptions : TransformOptions ) : string {
3976 // make sure react presets is registered in babelOptions
4077 this . _checkBabelOptions ( babelOptions ) ;
0 commit comments