diff --git a/package.json b/package.json index c583e55..d1de3af 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,6 @@ { "name": "laravel-vite-plugin", + "type": "module", "version": "0.8.1", "description": "Laravel plugin for Vite.", "keywords": [ @@ -32,14 +33,16 @@ "/inertia-helpers" ], "scripts": { - "build": "npm run build-plugin && npm run build-inertia-helpers", + "build": "npm run build-plugin && npm run build-inertia-helpers && npm run build-clean", "build-plugin": "rm -rf dist && npm run build-plugin-types && npm run build-plugin-esm && npm run build-plugin-cjs && cp src/dev-server-index.html dist/", "build-plugin-types": "tsc --emitDeclarationOnly", "build-plugin-cjs": "esbuild src/index.ts --platform=node --format=cjs --outfile=dist/index.cjs --define:import.meta.url=import_meta_url --inject:./import.meta.url-polyfill.js", "build-plugin-esm": "esbuild src/index.ts --platform=node --format=esm --outfile=dist/index.mjs", "build-inertia-helpers": "rm -rf inertia-helpers && tsc --project tsconfig.inertia-helpers.json", + "build-clean": "cp ./src/clean.js ./dist", "lint": "eslint --ext .ts ./src ./tests", - "test": "vitest run" + "test": "vitest run", + "clean-project": "node ./dist/clean.js" }, "devDependencies": { "@types/node": "^18.11.9", diff --git a/src/clean.js b/src/clean.js new file mode 100644 index 0000000..446f8b1 --- /dev/null +++ b/src/clean.js @@ -0,0 +1,56 @@ +import fs from 'fs' + +/* + * Argv helpers. + */ + +const argument = (name, fallback) => { + const index = process.argv.findIndex(argument => argument.startsWith(`--${name}=`)) + + return index === -1 + ? fallback() + : process.argv[index].substring(`--${name}=`.length) +} + +const option = (name) => process.argv.includes(`--${name}`) + +/* + * Configuration. + */ + +const dryRun = option('dry-run') +const root = argument('root', () => process.cwd()) +const manifestPath = argument('manifest-path', () => `${root}/public/build/manifest.json`) +const assetsDirectory = argument('asset-directory', () => `${root}/public/build/assets`) + +/* + * Clean. + */ + +console.log('Removing orphaned assets...') + +const manifest = JSON.parse(fs.readFileSync(manifestPath).toString()) + +const manifestAssets = Object.keys(manifest).map(key => manifest[key].file) + +const allAssets = fs.readdirSync(assetsDirectory, { withFileTypes: true }) + +const orphanedAssets = allAssets.filter(file => file.isFile()) + .filter(file => manifestAssets.findIndex(asset => asset.endsWith(`/${file.name}`)) === -1) + +if (orphanedAssets.length === 0) { + console.log('There are no ophaned assets.') +} else { + orphanedAssets.forEach(asset => { + const path = `${assetsDirectory}/${asset.name}` + + console.log(`Removing ${path}`) + + if (! dryRun) { + fs.unlinkSync(path) + } + }) + + console.log('Done cleaning.') +} +