Skip to content

Commit 3770ee3

Browse files
committed
feat: [utils] export importScript and lazyComponent
1 parent 735e869 commit 3770ee3

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-0
lines changed

src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import 'intersection-observer';
22

33
export { default as clsx } from 'clsx';
44

5+
export { importScript } from './utils/importScript';
6+
export { lazyComponent } from './utils/lazyComponent';
57
export { mountComponent } from './utils/mountComponent';
68
export { Avatar } from './components/Avatar';
79
export type { AvatarProps, AvatarSize, AvatarShape } from './components/Avatar';

src/utils/importScript.tsx

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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+
}

src/utils/lazyComponent.tsx

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
}

0 commit comments

Comments
 (0)