这里的问题在Error [ERR_REQUIRE_ESM]: Must use import to load ES Module
.
NodeJS 中有两种类型的模块:CommonJS和ECMAScript 模块(ESM)。
CommonJS 使用const webp = require("imagemin-webp")
语法。
而 ESM 使用import webp from "imagemin-webp"
语法来实现相同的结果。
你index.js
是 CommonJS 并且imagemin npm 模块是 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文档中所示。
它不是首选,因为它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();
PS
请注意,ESM 可以导出多个条目(默认和命名导出),而 CommonJS 只能导出一个条目。