在使用 Parcel V2 打包 Node.js 二进制文件时,需要使用 @parcel/transformer-raw 直接加载二进制文件。具体方法如下:
1.安装 transformer-raw:
npm install --save-dev @parcel/transformer-raw
2.在 .parcelrc 中添加 transformer-raw,或使用 CLI 命令:
{ "extends": "@parcel/config-default", "transforms": { "binary": ["@parcel/transformer-raw"] } }
3.在代码中加载二进制文件:
import fs from 'fs';
// 以读取图片为例 const img = fs.readFileSync('./my-image.png');
// 在其他地方使用 img 即可
注意:使用该方法打包二进制文件时,需要在打包后的文件中加入条件判断以兼容不同平台。例如,Windows 和 Unix 之间的路径分隔符不同。
示例代码如下:
// 读取文件 const readFile = path => { const file = fs.readFileSync(path); return file; };
// 判断是否为 Windows 系统 const isWindows = () => process.platform === 'win32';
// 将路径分隔符转换为当前系统的分隔符 const normalizePath = path => { if (isWindows()) { return path.replace(///g, '\'); } return path; };
// 加载二进制文件 const binaryFilePath = normalizePath('./binary-file.bin'); const binaryFile = readFile(binaryFilePath);
// 使用二进制文件 // ...
// 判断当前系统 if (isWindows()) { // Windows 系统下的处理逻辑 // ... } else { // Unix 系统下的处理逻辑 // ... }