Skip to content

Commit

Permalink
Introduce clean script
Browse files Browse the repository at this point in the history
  • Loading branch information
timacdonald committed Oct 8, 2023
1 parent 8e1a71a commit 349431e
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
File renamed without changes.
68 changes: 68 additions & 0 deletions bin/purge-orphaned-assets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#!/usr/bin/env node

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 quiet = option(`quiet`)
const root = argument(`root`, () => process.env.INIT_CWD)
const manifestPath = argument(`manifest-path`, () => `${root}/public/build/manifest.json`)
const assetsDirectory = argument(`asset-directory`, () => `${root}/public/build/assets`)

/*
* Helpers.
*/

const write = quiet ? (() => undefined) : console.log

/*
* Clean.
*/

write(`Reading manifest [${manifestPath}].`)

const manifest = JSON.parse(fs.readFileSync(manifestPath).toString())

const manifestAssets = Object.keys(manifest).map(key => manifest[key].file)

write(`Verify assets in [${assetsDirectory}].`)

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) {
write(`No ophaned assets found.`)
} else {
orphanedAssets.length === 1
? write(`[${orphanedAssets.length}] orphaned asset found.`)
: write(`[${orphanedAssets.length}] orphaned assets found.`)

orphanedAssets.forEach(asset => {
const path = `${assetsDirectory}/${asset.name}`

write(`Removing orphaned asset [${path}].`)

if (! dryRun) {
fs.unlinkSync(path)
}
})
}
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"name": "laravel-vite-plugin",
"type": "module",
"version": "0.8.1",
"description": "Laravel plugin for Vite.",
"keywords": [
Expand Down Expand Up @@ -31,6 +32,9 @@
"/dist",
"/inertia-helpers"
],
"bin": {
"purge-orphaned-assets": "bin/purge-orphaned-assets.js"
},
"scripts": {
"build": "npm run build-plugin && npm run build-inertia-helpers",
"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/",
Expand Down

0 comments on commit 349431e

Please sign in to comment.