hyde-vite-plugin
Version:
HydePHP Vite plugin for realtime compiler integration
1 lines • 1.85 kB
JavaScript
import fs from"fs";import path from"path";import{fileURLToPath}from"url";const HOT_FILE_PATH="app/storage/framework/runtime/vite.hot";function resolveResource(e){try{const s=fileURLToPath(import.meta.url),t=path.dirname(s);return path.resolve(t,"../resources",e)}catch(s){return path.resolve(__dirname,"../resources",e)}}function fileExists(e){try{return fs.statSync(e).isFile()}catch{return!1}}function hasJavaScriptContent(e){try{if(!fs.existsSync(e))return!1;return fs.readFileSync(e,"utf-8").replace(/\/\*[\s\S]*?\*\/|\/\/.*/g,"").trim().length>0}catch(e){return!1}}export default function hydePlugin(e={}){const{input:s=["resources/assets/app.css","resources/assets/app.js"],watch:t=["_pages","_posts","_docs"],refresh:r=!0}=e;let a,n;return{name:"hyde-vite-plugin",config(e,{command:t}){if("build"===t){const e={};for(const t of s){const s=path.resolve(process.cwd(),t);if(t.endsWith("app.js"))hasJavaScriptContent(s)&&fileExists(s)&&(e.js=s);else if(t.endsWith("app.css")&&fileExists(s))e.css=s;else if(fileExists(s)){e[path.basename(t,path.extname(t))]=s}}return{build:{outDir:"_media",emptyOutDir:!1,rollupOptions:{input:e,output:{entryFileNames:e=>"js"===e.name?"app.js":"[name].js",chunkFileNames:"[name].js",assetFileNames:e=>e.name&&e.name.endsWith(".css")?"app.css":"[name].[ext]"}}}}}},configResolved(e){a=e,n=path.resolve(process.cwd(),HOT_FILE_PATH)},configureServer(e){fs.mkdirSync(path.dirname(n),{recursive:!0}),fs.writeFileSync(n,""),["SIGINT","SIGTERM"].forEach((e=>{process.on(e,(()=>{try{fs.rmSync(n)}catch(e){}process.exit()}))})),e.middlewares.use(((e,s,t)=>{if("/"===e.url)try{const e=resolveResource("index.html"),t=fs.readFileSync(e,"utf-8");s.end(t)}catch(e){t()}else t()})),r&&t.forEach((s=>{const t=path.resolve(process.cwd(),s);fs.existsSync(t)&&(e.watcher.add(path.join(t,"**")),e.watcher.add(path.join(t,"**/**")))}))}}}