Files
Modrinth-plus/plugins/sveld.js

59 lines
1.9 KiB
JavaScript
Raw Normal View History

2022-05-20 00:10:45 -07:00
import { ComponentParser } from 'sveld';
import * as svelte from 'svelte/compiler';
import fs from 'fs/promises';
import path from 'path';
import { preprocess } from '../src/package/config/svelte.config.js';
export default function sveld() {
return {
name: 'vite-plugin-sveld',
async transform(src, id) {
if (id.endsWith('?raw&sveld')) {
2022-05-20 00:10:45 -07:00
const raw = JSON.parse(src.split('export default ')[1]);
2022-05-20 00:10:45 -07:00
const data = await parseRaw(raw, id);
return {
code: `export default ${JSON.stringify(data)}`,
2022-05-20 00:10:45 -07:00
map: null,
};
}
},
// This generates a `COMPONENT_API.json` with sveld in the `/_app` folder on build, which is used by the docs about components (only when built statically)
2022-03-30 14:05:15 -07:00
async buildStart() {
const output = {};
2022-05-20 00:10:45 -07:00
const componentFiles = await fs.readdir(path.resolve('./src/package/components'));
for (const fileName of componentFiles) {
2022-05-20 00:10:45 -07:00
const filePath = path.resolve('./src/package/components', fileName);
const raw = (await fs.readFile(filePath)).toString();
output[fileName] = await parseRaw(raw, filePath);
}
2022-03-30 14:05:15 -07:00
try {
2022-05-20 00:10:45 -07:00
await fs.mkdir(path.resolve('./src/generated'));
2022-03-30 14:05:15 -07:00
} catch {
// Do nothing, directory already exists
}
2022-05-20 00:10:45 -07:00
await fs.writeFile(
path.resolve('./src/generated/COMPONENT_API.json'),
JSON.stringify(output)
);
},
2022-05-20 00:10:45 -07:00
};
}
async function parseRaw(raw, filePath) {
let { code } = await svelte.preprocess(raw, preprocess, {
2022-05-20 00:10:45 -07:00
filename: filePath,
});
return new ComponentParser({
2022-05-20 00:10:45 -07:00
verbose: false,
}).parseSvelteComponent(code, {
filePath,
2022-05-20 00:10:45 -07:00
moduleName: filePath,
});
}