This project provides a tool to automatically compress PNG files in a specified directory using pngquant
. The tool watches the directory for new PNG files, compresses them, and renames the compressed files with a _compr
suffix. After compression, the original files are deleted.
The need to support ES modules in this application primarily stems from the fact that pngquant-bin
is an ES module. ES modules use a different syntax and have different behaviors compared to CommonJS modules, which is why ts-node and TypeScript need to be configured to handle ES modules correctly.
ES Modules require either the file to have a .mjs extension or to set "type": "module" in package.json.
- Watches a specified directory for new PNG files.
- Compresses PNG files using
pngquant
. - Renames compressed files with a
_compr
suffix. - Logs file size before and after compression.
- Deletes original files after compression.
-
node.js (v20 or higher)
-
npm (v10.2.4)
-
libimagequant
libimagequant is typically bundled with pngquant
brew install pngquant
sudo apt-get install libimagequant-dev
-
Clone the repository or download the source code.
git clone https://github.com/salcad/auto-png-compressor.git cd auto-png-compressor
-
Install the required npm packages.
npm install
-
Create a
.env
file in the root of the project and update theWATCHED_DIR
andCOMPRESSION_LEVEL
variables to match your needs.WATCHED_DIR=/path/to/your/folder COMPRESSION_LEVEL=50-70
-
Run the script in development mode.
npm run dev
-
To build and run the project in production mode:
npm run build npm start
-
Run test
npm test
- chokidar: A file watcher for Node.js.
- pngquant-bin: A pngquant binary for use in Node.js.
- ts-node: TypeScript execution environment for Node.js.
- typescript: TypeScript language and compiler.
- jest: JavaScript testing framework.
- ts-jest: Jest transformer for TypeScript.
- @types/node: TypeScript definitions for Node.js.
- @types/jest: TypeScript definitions for Jest.
Ensure your tsconfig.json
includes the following configuration to support ES modules and ts-node
:
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "node",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"typeRoots": ["./node_modules/@types", "./types"],
"resolveJsonModule": true,
"experimentalDecorators": true
},
"ts-node": {
"transpileOnly": true,
"esm": true,
"experimentalSpecifierResolution": "node"
},
"include": ["src/**/*", "types/**/*.d.ts"],
"exclude": ["node_modules", "dist", "tests"]
}