-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathsvelteComponent.ts
76 lines (62 loc) · 2.29 KB
/
svelteComponent.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* eslint-disable global-require */
import { ComponentPayload } from './types';
import mountComponentsInHtml from '../partialHydration/mountComponentsInHtml';
import getUniqueId from './getUniqueId';
export const getComponentName = (str) => {
let out = str.replace('.svelte', '').replace('.js', '');
if (out.includes('/')) {
out = out.split('/').pop();
}
return out;
};
const svelteComponent =
(componentName: String, folder: String = 'components') =>
({ page, props, hydrateOptions }: ComponentPayload): string => {
const { ssr, client } = page.settings.$$internal.findComponent(componentName, folder);
const cleanComponentName = getComponentName(componentName);
// eslint-disable-next-line import/no-dynamic-require
const ssrReq = require(ssr);
const { render, _css: css, _cssMap: cssMap } = ssrReq.default || ssrReq;
try {
const { html: htmlOutput, head } = render(props);
if (page.settings.css === 'inline') {
if (css && css.length > 0 && page.svelteCss && !hydrateOptions) {
page.svelteCss.push({ css, cssMap });
}
}
if (head && page.headStack) {
page.headStack.push({ source: cleanComponentName, priority: 50, string: head });
}
const innerHtml = mountComponentsInHtml({
html: htmlOutput,
page,
hydrateOptions,
});
// hydrateOptions.loading=none for server only rendered injected into html
if (!hydrateOptions || hydrateOptions.loading === 'none') {
// if a component isn't hydrated we don't need to wrap it in a unique div.
return innerHtml;
}
const id = getUniqueId();
const lowerCaseComponent = componentName.toLowerCase();
const uniqueComponentName = `${lowerCaseComponent}-ejs-${id}`;
page.componentsToHydrate.push({
name: uniqueComponentName,
hydrateOptions,
client,
props: Object.keys(props).length > 0 ? props : false,
prepared: {},
id,
});
return `<${
hydrateOptions.element
} class="${cleanComponentName.toLowerCase()}-component" id="${uniqueComponentName}">${innerHtml}</${
hydrateOptions.element
}>`;
} catch (e) {
// console.log(e);
page.errors.push(e);
}
return '';
};
export default svelteComponent;