ESBuild 错误:没有为“.node”文件配置加载程序:node_modules/sharp/build/Release/sharp.node

dea*_*904 9 node.js sharp esbuild

我正在尝试制作一个esbuild使用 Sharp 将 GIF 转换为 PNG 的插件,但出现以下错误:

\n
\n

\xe2\x9d\xaf npx esbuild .\\src\\utils\\gif-to-png.ts --platform=node --bundle\nnode_modules/sharp/lib/utility.js:7:22:错误:否加载器配置为“.node”文件:node_modules/sharp/build/Release/sharp.node\n7 \xe2\x94\x82 const Sharp = require(\'../build/Release/sharp.node\'); \n\xe2\x95\xb5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

\n
\n

gif 转 png.ts

\n
import fs from \'fs\'\nimport path from \'path\'\nimport sharp from \'sharp\'\nimport { Plugin } from \'esbuild\'\n\nconst ROOT_PATH = process.cwd()\nconst POSTS_PATH = path.join(ROOT_PATH, \'public\')\n\nfunction* walkSync(dir: fs.PathLike): any {\n    const files = fs.readdirSync(dir, { withFileTypes: true })\n    for (let i = 0; i < files.length; i++) {\n        if (files[i].isDirectory()) {\n            yield* walkSync(path.join(dir as string, files[i].name))\n        } else {\n            yield path.join(dir as string, files[i].name)\n        }\n    }\n}\n\nconst gifToPng = async () => {\n    try {\n        for (let [i, file] of [...walkSync(POSTS_PATH)].entries()) {\n            const extname = path.extname(file)\n            if (extname === \'.gif\') {\n                console.log(file)\n                const dirname = path.dirname(file)\n                const png = path.resolve(dirname, path.basename(file).replace(\'.gif\', \'.png\'))\n                await sharp(file).png().toFile(png)\n            }\n        }\n    } catch (e) {\n        console.error(\'Error thrown:\', e)\n    }\n}\n\nexport const gifToPngPlugin = (): Plugin => ({\n    name: \'gifToPng\',\n    setup(build) {\n        build.onLoad({ filter: /\\.gif$/ }, async (args) => {\n            const fileName = path.basename(args.path, \'.gif\')\n            let contents = await fs.promises.readFile(args.path, \'utf8\')\n            console.log({ fileName, contents })\n\n            return {\n                contents,\n                loader: \'file\',\n            }\n        })\n    },\n})\n
Run Code Online (Sandbox Code Playgroud)\n

我的代码仍在进行中,但我必须以某种方式调用gifToPng中的函数setup,以便将所有.gif文件转换为.png.

\n

如何解决.node加载器问题?

\n

编辑:

\n

事实证明,ESBuild 还不支持.node-> https://github.com/evanw/esbuild/issues/1051

\n

小智 3

我有类似的问题。我将此行添加到我的构建配置对象中。文档中可能有更好的解释:https ://esbuild.github.io/content-types/#file

build({    
  loader: { ".node": "file" },
  ...
})
Run Code Online (Sandbox Code Playgroud)