Mocha Image Compiler

raw JSON →
1.0.0 verified Fri May 01 auth: no javascript

Mocha compiler that enables webpack-like importing of images (PNG, JPG, GIF, SVG) in Node.js test environments. Current version 1.0.0 is stable and rarely updated. It works by replacing image require calls with a simple path string, making it ideal for testing components that import images. Unlike webpack loaders, this is a lightweight, no-config solution specifically designed for Mocha's --compilers flag. Requires Mocha as a peer dependency.

error Error: Cannot find module 'mocha-image-compiler'
cause Package not installed globally or missing in node_modules.
fix
Run npm install --save-dev mocha-image-compiler in your project.
error Error: compiler not found: mocha-image-compiler
cause Incorrect compiler syntax in --compilers flag.
fix
Use --compilers .:mocha-image-compiler (dot colon package-name). Ensure the dot matches the file extension (e.g., . for any extension, or .js:...).
error ReferenceError: require is not defined in ES module scope
cause Mocha is running with ESM ('type': 'module' in package.json) but using require() syntax.
fix
Add --experimental-modules or use import statements. Alternatively, set 'type': 'commonjs' or use .cjs extension.
gotcha Only works with Mocha's --compilers flag; does not support webpack or other bundlers.
fix Use only in Mocha test environment; for bundlers use appropriate loaders (e.g., file-loader).
gotcha Returns the file path as a string, not the actual image data or a module. This may differ from webpack behavior where require returns a URL or data URI.
fix Assume require('./image.png') returns a string path; do not expect a Buffer or URL object.
gotcha Requires Mocha to be installed separately; not included as a dependency.
fix Install mocha alongside mocha-image-compiler: npm install --save-dev mocha
gotcha Does not support dynamic require() calls; only static require paths are transformed.
fix Use only static string paths in require(); do not use variables or expressions.
gotcha May conflict with other Mocha compilers if not ordered correctly (e.g., with babel/register).
fix Specify compilers in correct order: mocha --compilers js:babel/register,.:mocha-image-compiler
npm install mocha-image-compiler
yarn add mocha-image-compiler
pnpm add mocha-image-compiler

Installs mocha and mocha-image-compiler, creates a test file that imports a PNG image, and runs mocha with the compiler to replace image require with a path string.

npm install --save-dev mocha mocha-image-compiler
echo "var logo = require('./logo.png'); console.log(logo);" > test.js
echo '{}' > package.json
mocha --compilers .:mocha-image-compiler test.js