2022-03-29 22:06:43 -07:00
import { ComponentParser } from 'sveld'
2022-03-29 00:44:23 -07:00
import sveltePreprocess from 'svelte-preprocess'
import * as svelte from 'svelte/compiler'
2022-03-29 22:06:43 -07:00
import fs from 'fs/promises'
import path from 'path'
2022-03-29 00:44:23 -07:00
export default function sveld ( ) {
return {
name : 'vite-plugin-sveld' ,
async transform ( src , id ) {
if ( id . endsWith ( '?raw&sveld' ) ) {
const raw = JSON . parse ( src . split ( 'export default ' ) [ 1 ] )
2022-03-29 22:06:43 -07:00
const data = await parseRaw ( raw , id )
2022-03-29 00:44:23 -07:00
return {
code : ` export default ${ JSON . stringify ( data ) } ` ,
map : null
}
}
2022-03-29 22:06:43 -07:00
} ,
// 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)
async generateBundle ( options , bundle ) {
const output = { } ;
const componentFiles = await fs . readdir ( path . resolve ( './src/lib/components' ) )
for ( const fileName of componentFiles ) {
const filePath = path . resolve ( './src/lib/components' , fileName )
const raw = ( await fs . readFile ( filePath ) ) . toString ( )
output [ fileName ] = await parseRaw ( raw , filePath )
}
this . emitFile ( {
type : 'asset' ,
fileName : 'COMPONENT_API.json' ,
source : JSON . stringify ( output ) ,
} )
} ,
2022-03-29 00:44:23 -07:00
}
2022-03-29 22:06:43 -07:00
}
async function parseRaw ( raw , filePath ) {
let { code } = await svelte . preprocess ( raw , sveltePreprocess ( { postcss : true } ) , {
filename : filePath
} )
return new ComponentParser ( {
verbose : false
} ) . parseSvelteComponent ( code , {
filePath ,
moduleName : filePath
} )
2022-03-29 00:44:23 -07:00
}