这里的问题在Error [ERR_REQUIRE_ESM]: Must use import to load ES Module。
NodeJS 中有两种类型的模块:CommonJS 和 ECMAScript modules (ESM)。
CommonJS 使用const webp = require("imagemin-webp") 语法。
而 ESM 使用 import webp from "imagemin-webp" 语法来实现相同的结果。
您的 index.js 是 CommonJS,imagemin npm module 是 ESM,当您尝试使用 require() 调用导入 ESM 模块时会出现错误。
对此有两种可能的解决方案:
- 将您的
index.js 从 CommonJS 转换为 ESM(首选)
- 使用异步
import()调用而不是require()从CommonJS导入ESM模块
第一个(也是首选)选项是将您的代码转换为 ESM:
- 将
index.js重命名为index.mjs(.mjs扩展名表示ESM语法)
- 将所有
require() 调用更改为import something from 'library' 调用
- 以
node index.mjs 运行它
index.mjs:
// using ES import syntax here
import imagemin from "imagemin";
import webp from "imagemin-webp";
// the rest of the file is unchanged
const outputFolder = "./images/webp";
const produceWebP = async () => {
await imagemin(["images/*.png"], {
destination: outputFolder,
plugins: [
webp({
lossless: true,
}),
],
});
console.log("PNGs processed");
await imagemin(["images/*.{jpg,jpeg}"], {
destination: outputFolder,
plugins: [
webp({
quality: 65,
}),
],
});
console.log("JPGs and JPEGs processed");
};
produceWebP();
第二个选项是使用异步 import() 调用从 CommonJS 模块导入 ESM 模块,如 NodeJS docs 所示。
由于import() 是异步的,所以不是首选,我想使用await 来获得类似await import() 的结果,但这又需要在另一个async 函数中调用。
index.js:
const outputFolder = "./images/webp";
const produceWebP = async () => {
// Load ESM modules using import(),
// it returns a Promise which resolves to
// default export as 'default' and other named exports.
// In this case we need default export.
const imagemin = (await import("imagemin")).default;
const webp = (await import("imagemin-webp")).default;
await imagemin(["images/*.png"], {
destination: outputFolder,
plugins: [
webp({
lossless: true,
}),
],
});
console.log("PNGs processed");
await imagemin(["images/*.{jpg,jpeg}"], {
destination: outputFolder,
plugins: [
webp({
quality: 65,
}),
],
});
console.log("JPGs and JPEGs processed");
};
produceWebP();
附言
请注意,ESM 可以导出多个条目(默认和命名导出),而 CommonJS 只能导出一个条目。