I am trying to make an esbuild
plugin that converts GIF to PNG using Sharp but I get the following error:
❯ npx esbuild .\src\utils\gif-to-png.ts --platform=node --bundle node_modules/sharp/lib/utility.js:7:22: error: No loader is configured for ".node" files: node_modules/sharp/build/Release/sharp.node 7 │ const sharp = require('../build/Release/sharp.node'); ╵ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
gif-to-png.ts
import fs from 'fs'
import path from 'path'
import sharp from 'sharp'
import { Plugin } from 'esbuild'
const ROOT_PATH = process.cwd()
const POSTS_PATH = path.join(ROOT_PATH, 'public')
function* walkSync(dir: fs.PathLike): any {
const files = fs.readdirSync(dir, { withFileTypes: true })
for (let i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
yield* walkSync(path.join(dir as string, files[i].name))
} else {
yield path.join(dir as string, files[i].name)
}
}
}
const gifToPng = async () => {
try {
for (let [i, file] of [...walkSync(POSTS_PATH)].entries()) {
const extname = path.extname(file)
if (extname === '.gif') {
console.log(file)
const dirname = path.dirname(file)
const png = path.resolve(dirname, path.basename(file).replace('.gif', '.png'))
await sharp(file).png().toFile(png)
}
}
} catch (e) {
console.error('Error thrown:', e)
}
}
export const gifToPngPlugin = (): Plugin => ({
name: 'gifToPng',
setup(build) {
build.onLoad({ filter: /\.gif$/ }, async (args) => {
const fileName = path.basename(args.path, '.gif')
let contents = await fs.promises.readFile(args.path, 'utf8')
console.log({ fileName, contents })
return {
contents,
loader: 'file',
}
})
},
})
My code is still a work in progress but I have to somehow call gifToPng
function in the setup
so it converts all .gif
files to .png
.
How do I solve the .node
loader issue?
Edit:
Turns out, ESBuild doesn't support .node
yet -> https://github.com/evanw/esbuild/issues/1051