File tree Expand file tree Collapse file tree 3 files changed +67
-0
lines changed Expand file tree Collapse file tree 3 files changed +67
-0
lines changed Original file line number Diff line number Diff line change @@ -2,6 +2,8 @@ import 'intersection-observer';
2
2
3
3
export { default as clsx } from 'clsx' ;
4
4
5
+ export { importScript } from './utils/importScript' ;
6
+ export { lazyComponent } from './utils/lazyComponent' ;
5
7
export { mountComponent } from './utils/mountComponent' ;
6
8
export { Avatar } from './components/Avatar' ;
7
9
export type { AvatarProps , AvatarSize , AvatarShape } from './components/Avatar' ;
Original file line number Diff line number Diff line change
1
+ export function importScript ( url : string , name : string ) {
2
+ return new Promise ( ( resolve , reject ) => {
3
+ const script = document . createElement ( 'script' ) ;
4
+ script . async = true ;
5
+
6
+ const destroy = ( ) => {
7
+ if ( script . parentNode ) {
8
+ script . parentNode . removeChild ( script ) ;
9
+ }
10
+ if ( name && window [ name as any ] ) {
11
+ delete window [ name as any ] ;
12
+ }
13
+ } ;
14
+
15
+ script . onload = ( ) => {
16
+ resolve ( window [ name as any ] ) ;
17
+ destroy ( ) ;
18
+ } ;
19
+
20
+ script . onerror = ( ) => {
21
+ reject ( new Error ( `Failed to import: ${ url } ` ) ) ;
22
+ destroy ( ) ;
23
+ } ;
24
+
25
+ script . src = url ;
26
+ document . head . appendChild ( script ) ;
27
+ } ) ;
28
+ }
Original file line number Diff line number Diff line change
1
+ import React from 'react' ;
2
+ import { importScript } from './importScript' ;
3
+
4
+ export type LazyComponentResult = React . LazyExoticComponent < React . ComponentType < any > > & {
5
+ WrappedComponent ?: React . ComponentType < any > ;
6
+ } ;
7
+
8
+ export function lazyComponent (
9
+ url : string ,
10
+ name : string ,
11
+ success ?: ( ) => void ,
12
+ fail ?: ( err : Error ) => void ,
13
+ ) {
14
+ const ret : LazyComponentResult = React . lazy ( ( ) =>
15
+ importScript ( url , name )
16
+ . then ( ( res : any ) => {
17
+ if ( ! res . default ) {
18
+ throw new Error ( `Failed to import ${ name } component: no default export` ) ;
19
+ }
20
+
21
+ ret . WrappedComponent = res . default || res ;
22
+
23
+ if ( success ) {
24
+ success ( ) ;
25
+ }
26
+ return res ;
27
+ } )
28
+ . catch ( ( err : any ) => {
29
+ if ( fail ) {
30
+ fail ( err ) ;
31
+ }
32
+ return { default : ( ) => < > </ > } ;
33
+ } ) ,
34
+ ) ;
35
+
36
+ return ret ;
37
+ }
You can’t perform that action at this time.
0 commit comments