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

k0pti3hp  于 9个月前  发布在  Gulp
关注(0)|答案(1)|浏览(158)

我有一个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"
      }
}


我已经查过了,但没有一个答案对我有用

cgfeq70w

cgfeq70w1#

这是由于你最初编写的代码没有动态导入而导致的问题。你可以看看我下面给予的代码作为例子,并做出相应的修改。
1.在package.json中添加了“type”:“module”。
1.将“require”语句更改为“import”,并添加Sass作为gulp-sass编译器:按照下面的示例更改代码:
从“gulp”导入gulp;
const { src,dest,series,watch } = gulp;
从“gulp-sass”导入gulpSass;
从“gulp-autofixer”导入autofixer;
从“gulp-clean-css”导入cssMinify;
从“gulp-terser”导入jsMinify;
import * as sass from“sass”;
const scss = gulpSass(sass);
注意事项:如果你在app.js中的jsx模型中做了一个输入,你可能会得到一个反相错误。比如你在app.js中输入rafce保存后会得到这个错误。原因有点复杂,我没有完整的命令。PluginError [SyntaxError]:Unexpected token:operator(<)。如果你得到这个错误,按照我说的做。
如果问题没有解决,请按照以下方式更改代码。您可以在此代码上进行自己的更改:

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%肯定的解决方案。尝试在您的项目的变化。

相关问题