You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gulp中ES模块环境下require()不支持的问题解决方法

Node.js中Gulp模块兼容问题解决方案

问题背景

项目package.json配置了"type": "module"(ES模块模式),但gulpfile.js使用CommonJS的require()语法引入模块,运行Gulp时触发如下错误:

Error [ERR_REQUIRE_ESM]: require() of ES Module index.js from gulpfile.js not supported.
Instead change the require of index.js in gulpfile.js to a dynamic import() which is available in all CommonJS modules.
at Object. (gulpfile.js:3:18)
at async Promise.all (index 0) {
code: 'ERR_REQUIRE_ESM'
}

相关文件内容

gulpfile.js

'use strict';
const gulp = require("gulp");
const imagemin = require("gulp-imagemin");
const webp = require("imagemin-webp");
const extReplace = require("gulp-ext-replace");

gulp.task("exportWebP", function() {
  let src = "artists/**/*.jpg"; // 原始图片路径
  let dest = "dist/images"; // WebP图片输出路径

  return gulp.src(src)
    .pipe(imagemin([
      webp({
        quality: 75
      })
    ]))
    .pipe(extReplace(".webp"))
    .pipe(gulp.dest(dest));
});

package.json

{
  "type": "module",
  "main": "gulpfile.js",
  "dependencies": {
    "gulp-ext-replace": "^0.3.0",
    "gulp-imagemin": "^8.0.0",
    "imagemin-webp": "^7.0.0"
  },
  "devDependencies": {
    "gulp": "^4.0.2"
  }
}

解决方案

提供三种可行方案,可根据项目需求选择:

方案1:将gulpfile转为ES模块语法

把require()替换为import语法,同时调整Gulp任务的导出方式(ES模块下需使用导出语法定义任务):

修改后的gulpfile.js:

import gulp from 'gulp';
import imagemin from 'gulp-imagemin';
import webp from 'imagemin-webp';
import extReplace from 'gulp-ext-replace';

export const exportWebP = () => {
  const src = "artists/**/*.jpg";
  const dest = "dist/images";

  return gulp.src(src)
    .pipe(imagemin([
      webp({ quality: 75 })
    ]))
    .pipe(extReplace(".webp"))
    .pipe(gulp.dest(dest));
};

// 如需设置默认任务,可添加
// export default exportWebP;

运行时执行gulp exportWebP即可。

方案2:移除package.json中的"type": "module"

如果项目无需强制使用ES模块,删除package.json里的"type": "module"配置,让Node.js默认以CommonJS模式处理文件,原gulpfile.js无需修改即可正常运行。

修改后的package.json片段:

{
  "main": "gulpfile.js",
  // 移除"type": "module"配置项
  "dependencies": {
    // 依赖内容保持不变
  }
}

方案3:重命名gulpfile为CommonJS格式

保留package.json的"type": "module"配置,将gulpfile.js重命名为gulpfile.cjs,明确指定该文件使用CommonJS语法,原代码无需修改。

运行Gulp时,工具会自动识别gulpfile.cjs,直接执行gulp exportWebP即可。


内容的提问来源于stack exchange,提问作者Aaron Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 10:05:36