简体   繁体   中英

ESBuild error: No loader is configured for ".node" files: node_modules/sharp/build/Release/sharp.node

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

I had similar issue. I added this line to my build config object. Probably better explanation in the docs: https://esbuild.github.io/content-types/#file

build({    
  loader: { ".node": "file" },
  ...
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM