astro/snowpack-plugin.cjs

71 lines
2.4 KiB
JavaScript
Raw Normal View History

const { readFile } = require('fs').promises;
2021-03-15 17:22:05 +00:00
// Snowpack plugins must be CommonJS :(
const transformPromise = import('./lib/transform2.js');
2021-03-15 17:22:05 +00:00
module.exports = function (snowpackConfig, { resolve } = {}) {
return {
name: 'snowpack-hmx',
knownEntrypoints: ['deepmerge'],
2021-03-15 17:22:05 +00:00
resolve: {
input: ['.hmx', '.md'],
output: ['.js'],
2021-03-15 17:22:05 +00:00
},
async load({ filePath }) {
const { compilePage, compileComponent } = await transformPromise;
const projectRoot = snowpackConfig.root;
const contents = await readFile(filePath, 'utf-8');
2021-03-15 17:22:05 +00:00
if (!filePath.includes('/pages/') && !filePath.includes('/layouts/')) {
const result = await compileComponent(contents, { compileOptions: { resolve }, filename: filePath, projectRoot });
2021-03-15 17:22:05 +00:00
return result.contents;
}
const result = await compilePage(contents, {
compileOptions: { resolve },
filename: filePath,
projectRoot,
});
2021-03-15 17:22:05 +00:00
try {
return /* js */ `
2021-03-15 17:22:05 +00:00
${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],
2021-03-15 17:22:05 +00:00
[...(childRenderFns || []), renderHmx]
);
}
const data = merge.all([_data, ...(childDatas || [])]);
let headResult;
2021-03-15 17:22:05 +00:00
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),
]);
2021-03-15 17:22:05 +00:00
};
`;
} catch (err) {
console.error(err);
}
return result.contents;
},
};
};