-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
snowpack-plugin.cjs
70 lines (64 loc) · 2.42 KB
/
snowpack-plugin.cjs
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
const { readFile } = require('fs').promises;
// Snowpack plugins must be CommonJS :(
const transformPromise = import('./lib/transform2.js');
module.exports = function (snowpackConfig, { resolve } = {}) {
return {
name: 'snowpack-hmx',
knownEntrypoints: ['deepmerge'],
resolve: {
input: ['.hmx', '.md'],
output: ['.js'],
},
async load({ filePath }) {
const { compilePage, compileComponent } = await transformPromise;
const projectRoot = snowpackConfig.root;
const contents = await readFile(filePath, 'utf-8');
if (!filePath.includes('/pages/') && !filePath.includes('/layouts/')) {
const result = await compileComponent(contents, { compileOptions: { resolve }, filename: filePath, projectRoot });
return result.contents;
}
const result = await compilePage(contents, {
compileOptions: { resolve },
filename: filePath,
projectRoot,
});
try {
return /* js */ `
${result.contents}
export default async (childDatas, childRenderFns) => {
// Kind of hacky, can clean up if this works
const renderHmx = {setup, head, body};
const merge = (await import('deepmerge')).default;
const content = childDatas && childDatas[0].content;
const _data = await renderHmx.setup({content});
if (_data.layout) {
const renderLayout = (await import('/_hmx/layouts/' + _data.layout.replace(/.*layouts\\//, "").replace(/\.hmx$/, '.js'))).default;
return renderLayout(
[...(childDatas || []), _data],
[...(childRenderFns || []), renderHmx]
);
}
const data = merge.all([_data, ...(childDatas || [])]);
let headResult;
let bodyResult;
for (const renderFn of (childRenderFns || [])) {
let headAndBody = await Promise.all([
renderFn.head(data, headResult),
renderFn.body(data, bodyResult)
]);
headResult = headAndBody[0];
bodyResult = headAndBody[1];
}
return h(Fragment, null, [
renderHmx.head(data, headResult, true),
renderHmx.body(data, bodyResult, true),
]);
};
`;
} catch (err) {
console.error(err);
}
return result.contents;
},
};
};