错误 [ERR_REQUIRE_ESM]:gulpfile.js 中 ES 模块的 require()

问题描述 投票:0回答:1

我有一个 React16 项目,我正在尝试将其更新到 React18,使用旧包一切正常。但我更新了所有包和依赖项,当我想运行它时,它返回此错误:

$ npx gulp wds
Error [ERR_REQUIRE_ESM]: require() of ES Module E:\project\frontend\node_modules\gulp-rev\index.js from E:\project\frontend\gulpfile.js not supported.
Instead change the require of index.js in E:\project\frontend\gulpfile.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (E:\project\frontend\gulpfile.js:6:13) {
  code: 'ERR_REQUIRE_ESM'
}

myold gulpfile.js

const gulp = require('gulp');
const gutil = require('gulp-util');
const plumber = require('gulp-plumber');
const sourcemaps = require('gulp-sourcemaps');
const rename = require('gulp-rename'); // переименование файлов
const rev = require('gulp-rev');
const revManifest = require('gulp-revmanifest');
const webpack = require('webpack');
const sass = require('gulp-sass'); // препроцессор sass
const postcss = require('gulp-postcss'); // PostCSS core
const autoprefixer = require('autoprefixer'); // расстановка вендорных префиксов
const csso = require('gulp-csso'); // минификация css, единственный работает корректно с sourcemaps
const WebpackDevServer = require('webpack-dev-server');
const webpackConfigProd = require('./webpack.prod');
const wdsConfig = require('./webpack.wds');

const path = {
  // откуда брать исходники:
  src: {
    css: './sass/app.scss',
    fonts: './../assets/fonts/roboto/*.*',
  },
  // куда складывать готовые после сборки файлы:
  dist: {
    css: './../assets/css/',
    fonts: './../assets/fonts/',
    manifestDir: './../',
    manifest: './../ver.json',
  },
  // за изменением каких файлов мы хотим наблюдать
  watch: {
    js: './**/*.js',
    css: './**/*.scss*',
  },
};
gulp.task('wds', () => {
  gulp.watch([path.watch.css], gulp.series('css:build'));
  // Start a webpack-dev-server
  new WebpackDevServer(webpack(wdsConfig), {
    publicPath: '/',
    contentBase: './../assets',
    historyApiFallback: {
      index: 'index.html',
    },
    stats: {
      colors: true,
    },
  }).listen(8089, 'localhost', err => {
    if (err) throw new gutil.PluginError('webpack-dev-server', err);
    gutil.log('[webpack-dev-server]', './../assets/index.html');
  });
});

gulp.task('webpack', callback => {
  webpack(webpackConfigProd, (err, stats) => {
    if (err) {
      throw new gutil.PluginError('webpack', err);
    }
    gutil.log('[webpack]', stats.toString({}));
    callback();
  });
});

// watch
gulp.task('watch', () => {
  // билд css в случае изменения
  gulp.watch([path.watch.css], gulp.series('css:build'));
  // билд js
  gulp.watch([path.watch.js], gulp.series('webpack'));
});

// билд css
gulp.task('css:build', () => {
  const ap = [autoprefixer()];
  return gulp
    .src(path.src.css)
    .pipe(plumber())
    .pipe(sourcemaps.init()) // инициализируем sourcemap
    .pipe(sass().on('error', sass.logError)) // скомпилировать sass
    .pipe(sourcemaps.write({ includeContent: false }))
    .pipe(sourcemaps.init({ loadMaps: true }))
    .pipe(postcss(ap)) // добавить вендорные префиксы
    .pipe(gulp.dest(path.dist.css)) // вызгрузить в dist немин. версию
    .pipe(csso({ debug: false })) // минификация
    .pipe(sourcemaps.write({ includeContent: false }))
    .pipe(rename({ suffix: '.min' }))
    .pipe(gulp.dest(path.dist.css)) // вызгрузить в build мин.версию
    .pipe(rev())
    .pipe(
      revManifest(path.dist.manifest, {
        merge: true,
      })
    )
    .pipe(gulp.dest(path.dist.manifestDir));
});

我的新 gulpfile.js

import gulp from 'gulp';
import gutil from 'gulp-util';
import plumber from 'gulp-plumber';
import sourcemaps from 'gulp-sourcemaps';
import rename from 'gulp-rename'; // переименование файлов
import rev from 'gulp-rev';
import revManifest from 'gulp-revmanifest';
import webpack from 'webpack';
import sass from 'gulp-sass'; // препроцессор sass
import postcss from 'gulp-postcss'; // PostCSS core
import autoprefixer from 'autoprefixer'; // расстановка вендорных префиксов
import csso from 'gulp-csso'; // минификация css, единственный работает корректно с sourcemaps
import WebpackDevServer from 'webpack-dev-server';
import webpackConfigProd from './webpack.prod';
import wdsConfig from './webpack.wds';

const path = {
  // откуда брать исходники:
  src: {
    css: './sass/app.scss',
    fonts: './../assets/fonts/roboto/*.*',
  },
  // куда складывать готовые после сборки файлы:
  dist: {
    css: './../assets/css/',
    fonts: './../assets/fonts/',
    manifestDir: './../',
    manifest: './../ver.json',
  },
  // за изменением каких файлов мы хотим наблюдать
  watch: {
    js: './**/*.js',
    css: './**/*.scss*',
  },
};
gulp.task('wds', () => {
  gulp.watch([path.watch.css], gulp.series('css:build'));
  // Start a webpack-dev-server
  new WebpackDevServer(webpack(wdsConfig), {
    publicPath: '/',
    contentBase: './../assets',
    historyApiFallback: {
      index: 'index.html',
    },
    stats: {
      colors: true,
    },
  }).listen(8089, 'localhost', err => {
    if (err) throw new gutil.PluginError('webpack-dev-server', err);
    gutil.log('[webpack-dev-server]', './../assets/index.html');
  });
});

gulp.task('webpack', callback => {
  webpack(webpackConfigProd, (err, stats) => {
    if (err) {
      throw new gutil.PluginError('webpack', err);
    }
    gutil.log('[webpack]', stats.toString({}));
    callback();
  });
});

// watch
gulp.task('watch', () => {
  // билд css в случае изменения
  gulp.watch([path.watch.css], gulp.series('css:build'));
  // билд js
  gulp.watch([path.watch.js], gulp.series('webpack'));
});

// билд css
gulp.task('css:build', () => {
  const ap = [autoprefixer()];
  return gulp
    .src(path.src.css)
    .pipe(plumber())
    .pipe(sourcemaps.init()) // инициализируем sourcemap
    .pipe(sass().on('error', sass.logError)) // скомпилировать sass
    .pipe(sourcemaps.write({ includeContent: false }))
    .pipe(sourcemaps.init({ loadMaps: true }))
    .pipe(postcss(ap)) // добавить вендорные префиксы
    .pipe(gulp.dest(path.dist.css)) // вызгрузить в dist немин. версию
    .pipe(csso({ debug: false })) // минификация
    .pipe(sourcemaps.write({ includeContent: false }))
    .pipe(rename({ suffix: '.min' }))
    .pipe(gulp.dest(path.dist.css)) // вызгрузить в build мин.версию
    .pipe(rev())
    .pipe(
      revManifest(path.dist.manifest, {
        merge: true,
      })
    )
    .pipe(gulp.dest(path.dist.manifestDir));
});

我的 package.json 文件

{
    "name": "floxis-catalog-ui",
    "version": "1.0.0",
    "author": "Floxis",
    "license": "ISC",
    "description": "Floxis Catalog UI",
    "repository": "https://gitlab.com/floxis/floxis-catalog-ui",
    "scripts": {
        "lint": "eslint . --ext .js,.jsx,.ts,.tsx",
        "lint-fix": "eslint . --fix --ext .js,.jsx,.ts,.tsx",
        "local": "npx gulp wds",
        "test": "node scripts/test.js --no-cache",
        "tsc": "tsc",
        "validate": "npm run lint && npm run tsc"
    },
    "type": "module",
    "browserslist": [
        "last 4 version",
        "> 1%",
        "iOS > 6"
    ],
    "dependencies": {
        "@babel/polyfill": "7.2.5",
        "@babel/runtime": "7.21.0",
        "@types/react-resize-detector": "^5.0.0",
        "axios": "^1.3.4",
        "chroma-js": "^2.4.2",
        "core-js": "^3.29.1",
        "date-fns": "^2.29.3",
        "history": "^5.3.0",
        "i18next": "^22.4.13",
        "i18next-icu": "^2.1.0",
        "i18next-xhr-backend": "^3.2.2",
        "immutability-helper": "^3.1.1",
        "lodash": "^4.17.21",
        "md5": "^2.3.0",
        "memoize-one": "^6.0.0",
        "moment": "2.29.4",
        "moment-timezone": "^0.5.41",
        "nanoid": "^4.0.1",
        "query-string": "^8.1.0",
        "react": "18.2.0",
        "react-app-polyfill": "^3.0.0",
        "react-bootstrap-toggle": "^2.3.2",
        "react-calendar": "^4.0.0",
        "react-content-loader": "^6.2.1",
        "react-datepicker": "^4.10.0",
        "react-dom": "18.2.0",
        "react-i18next": "^12.2.0",
        "react-infinite-scroller": "^1.2.6",
        "react-input-mask": "2.0.4",
        "react-query": "3.39.3",
        "react-redux": "8.0.5",
        "react-remove-scroll": "^2.5.5",
        "react-resize-detector": "^8.0.4",
        "react-responsive": "^9.0.2",
        "react-router": "^6.9.0",
        "react-router-dom": "6.9.0",
        "react-router-hash-link": "^2.4.3",
        "react-select": "5.7.1",
        "react-textarea-autosize": "^8.4.1",
        "react-tooltip": "^5.10.0",
        "redux": "4.2.1",
        "redux-axios": "0.0.2",
        "redux-thunk": "2.4.2",
        "scrollreveal": "^4.0.9",
        "swiper": "^9.1.1",
        "tracekit": "^0.4.6",
        "uuid": "^9.0.0"
      },
    "devDependencies": {
        "@babel/core": "^7.21.3",
        "@babel/plugin-proposal-class-properties": "7.18.6",
        "@babel/plugin-proposal-export-default-from": "^7.18.10",
        "@babel/plugin-proposal-export-namespace-from": "^7.18.9",
        "@babel/plugin-proposal-optional-chaining": "^7.21.0",
        "@babel/plugin-proposal-throw-expressions": "^7.18.6",
        "@babel/plugin-syntax-dynamic-import": "^7.8.3",
        "@babel/plugin-transform-modules-commonjs": "^7.21.2",
        "@babel/plugin-transform-runtime": "7.21.0",
        "@babel/preset-env": "7.20.2",
        "@babel/preset-react": "7.18.6",
        "@babel/preset-typescript": "^7.21.0",
        "@testing-library/react": "^14.0.0",
        "@types/enzyme": "^3.10.12",
        "@types/react": "^18.0.28",
        "@types/react-dom": "^18.0.11",
        "@types/react-router-dom": "^5.3.3",
        "@typescript-eslint/eslint-plugin": "^5.56.0",
        "@typescript-eslint/parser": "^5.56.0",
        "autoprefixer": "^10.4.14",
        "babel-cli": "^6.26.0",
        "babel-eslint": "10.0.1",
        "babel-jest": "^29.5.0",
        "babel-loader": "9.1.2",
        "babel-preset-react-app": "^10.0.1",
        "camelcase": "^7.0.1",
        "css-loader": "6.7.3",
        "cssnano": "^5.1.15",
        "enzyme": "^3.11.0",
        "eslint": "^8.36.0",
        "eslint-config-airbnb": "19.0.4",
        "eslint-config-prettier": "^8.8.0",
        "eslint-config-standard": "^17.0.0",
        "eslint-plugin-import": "2.27.5",
        "eslint-plugin-jsx-a11y": "6.7.1",
        "eslint-plugin-node": "^11.1.0",
        "eslint-plugin-prettier": "^4.2.1",
        "eslint-plugin-promise": "^6.1.1",
        "eslint-plugin-react": "^7.32.2",
        "eslint-plugin-standard": "^4.1.0",
        "express": "latest",
        "gulp": "latest",
        "gulp-csso": "latest",
        "gulp-html-beautify": "latest",
        "gulp-imagemin": "latest",
        "gulp-plumber": "latest",
        "gulp-postcss": "latest",
        "gulp-pug": "latest",
        "gulp-rename": "latest",
        "gulp-rev": "latest",
        "gulp-revmanifest": "latest",
        "gulp-sass": "latest",
        "gulp-sourcemaps": "latest",
        "gulp-typograf": "latest",
        "gulp-util": "latest",
        "gulp-watch": "latest",
        "identity-obj-proxy": "^3.0.0",
        "jest": "^29.5.0",
        "jest-dom": "^4.0.0",
        "jest-environment-jsdom-fourteen": "^1.0.1",
        "jest-resolve": "29.5.0",
        "jest-watch-typeahead": "2.2.2",
        "npx": "^10.2.2",
        "postcss-loader": "^7.1.0",
        "prettier": "^2.8.6",
        "react-dev-utils": "^12.0.1",
        "source-map": "latest",
        "source-map-loader": "^4.0.1",
        "style-loader": "3.3.2",
        "ts-jest": "^29.0.5",
        "ts-loader": "^9.4.2",
        "typescript": "^5.0.2",
        "webpack": "^5.76.3",
        "webpack-cli": "^5.0.1",
        "webpack-dev-server": "^4.13.1",
        "webpack-encoding-plugin": "^0.3.1",
        "webpack-merge": "^5.8.0"
      }
}

我对此进行了搜索,但没有一个答案对我有用

webpack gulp
1个回答
0
投票

这是你先写的代码没有动态导入导致的问题。您可以查看我下面给出的示例代码并进行相应的更改。

  1. 在 package.json 中添加了“type”:“module”。

  2. 将“require”语句更改为“import”并添加 Sass 作为 gulp-sass 编译器:更改您的代码,如下例所示:

    从“gulp”导入gulp;

    const { src, dest, 系列, watch } = gulp;

    从“gulp-sass”导入gulpSass;

    从“gulp-autoprefixer”导入autoPrefixer;

    从“gulp-clean-css”导入 cssMinify;

    从“gulp-terser”导入jsMinify;

    从“sass”导入*作为sass;

    const scss = gulpSass(sass);

注意:如果您在 app.js 中输入 jsx 模型,您可能会收到反转错误。例如,在 app.js 中键入 rafce 保存后,您可能会收到此错误。原因有点复杂,我也没有完全掌握。插件错误 [语法错误]:意外的标记:运算符 (<). If you get this error, do as I said.

如果问题没有解决,请按如下方式更改代码。您可以对此代码进行自己的更改:

import gulp from "gulp";
const { src, dest, series, watch } = gulp;

import gulpSass from "gulp-sass";
import autoPrefixer from "gulp-autoprefixer";
import cssMinify from "gulp-clean-css";
import jsMinify from "gulp-terser";
import * as sass from "sass";
const scss = gulpSass(sass);

function styles() {
  return src("./frontend/src/styles/**/*.scss")
    .pipe(scss())
    .pipe(autoPrefixer("last 2 versions"))
    .pipe(cssMinify())
    .pipe(dest("./frontend/dist/styles/"));
}
function scripts() {
  return src("./frontend/src/scripts/**/*.js")
    .pipe(jsMinify())
    .pipe(dest("./frontend/dist/scripts/"));
}

function watchTask() {
  watch(
    ["./frontend/src/styles/**/*.scss", "./frontend/src/scripts/**/*.js"],
    series(styles, scripts)
  );
}

export default series(styles, scripts, watchTask);

如果您遇到其他错误,请告诉我。 100%确定的解决方案。尝试在您的项目中对此进行更改。

© www.soinside.com 2019 - 2024. All rights reserved.