javascriptjsonvue.jsvite

How to minify json files while Vite build?


I have a project on Vite + Vue.js, and there are many large static reference files in public/data with .json extension. How can I minify them during build without turning them into javascript?

I tried to do it via esbuild:

esbuild public/data/*.json --outdir=/dist/public/data/ --allow-overwrite --minify

but it makes .js output files with module export [...] I don't need that, since I get them at runtime via fetch as needed, not via import.

I whant only minify pretty-print spaces, tabs and new lines inside json.


Solution

  • Here is the solution to my problem:

    yarn add jsonminify -D
    

    Then I created a /minify-data.js:

    import fs from 'fs'
    import path from 'path'
    import jsonminify from 'jsonminify'
    import { fileURLToPath } from 'url'
    
    const __dirname = path.dirname(fileURLToPath(import.meta.url))
    
    //this is the target path of my json files, copyed from `./public/data` by Vite
    const publicDir = path.resolve(__dirname, './dist/data')
    
    //recursively call jsonminify to json files in directory
    const minifyJsonFiles = dir => {
        fs.readdirSync(dir).forEach(file => {
            const filePath = path.join(dir, file)
            const stat = fs.statSync(filePath)
    
            if (stat.isDirectory()) {
                minifyJsonFiles(filePath)
            } else if (path.extname(file) === '.json') {
                const content = fs.readFileSync(filePath, 'utf8')
                const minifiedContent = jsonminify(content)
                fs.writeFileSync(filePath, minifiedContent)
                console.log(`Minified: ${filePath}`)
            }
        })
    }
    
    minifyJsonFiles(publicDir)
    

    And finaly I appended build command in package.json:

    "scripts": {
       "dev": "vite",
       "build": "vite build && node minify-data.js",
       ...
    },
    

    It works slowly but it does what I need it to.