Skip to content
This repository was archived by the owner on Jul 6, 2025. It is now read-only.

Commit 12f41c1

Browse files
author
Je
committed
breaking: rewrite Import component
1 parent 0e971a5 commit 12f41c1

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

import.ts

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import React, { ComponentType, ReactElement, useEffect, useState } from 'https://esm.sh/react'
2+
import util, { reModuleExt } from './util.ts'
3+
4+
interface ImportProps {
5+
from: string
6+
name?: string // default is 'default'
7+
props?: Record<string, any>
8+
fallback?: ReactElement
9+
}
10+
11+
export default function Import(props: ImportProps) {
12+
const { __importer, __sourceFile } = (props as any)
13+
const [error, setError] = useState<string | null>(null)
14+
const [mod, setMod] = useState<{ Component: ComponentType | null }>({ Component: null })
15+
16+
useEffect(() => {
17+
if (reModuleExt.test(__sourceFile)) {
18+
const p = util.splitPath(__importer)
19+
p.pop()
20+
import(util.cleanPath('/_aleph/' + p.join('/') + '/' + props.from))
21+
.then(mod => {
22+
const Component = mod[props.name || 'default']
23+
if (util.isLikelyReactComponent(Component)) {
24+
setMod({ Component })
25+
} else {
26+
setError(`component${props.name ? ` '${props.name}'` : ''} not found`)
27+
}
28+
})
29+
.catch((err: Error) => {
30+
setError(err.message)
31+
})
32+
}
33+
}, [__importer, __sourceFile])
34+
35+
if (error) {
36+
return React.createElement('div', { style: { color: 'red' } }, error)
37+
}
38+
39+
if (mod.Component) {
40+
return React.createElement(mod.Component, props.props)
41+
}
42+
43+
if (reModuleExt.test(__sourceFile) && props.fallback) {
44+
return props.fallback
45+
}
46+
47+
return null
48+
}

0 commit comments

Comments
 (0)