0

搞了一天,我不明白为什么 babel for gulp 对我不起作用,或者我错误地连接了模块......
浏览器中的错误是这样的:

Uncaught ReferenceError: require is not defined
  at main.min.js:1

我像这样连接模块:

import focusVisible from "focus-visible";

main.min.js 文件中的代码:

"use strict";var e;(e=require("focus-visible"))&&e.__esModule;

吞咽任务:

const { src, dest, series, watch, parallel } = require('gulp'),
      fileinclude = require('gulp-file-include'),
      rename = require("gulp-rename"),
      uglify = require('gulp-uglify-es').default,
      babel = require("gulp-babel"),
      notify = require("gulp-notify"),
      browserSync = require("browser-sync").create()

const changingScripts = () => {
  return src(['src/js/main.js', 'src/js/pages/**/*.js'])
    .pipe(babel())
    .pipe(fileinclude())
    .pipe(dest('dist/js'))
    .pipe(uglify({
      toplevel: true
    }).on('error', notify.onError()))
    .pipe(rename({
      extname: '.min.js'
    }))
    .pipe(dest('dist/js'))
    .pipe(browserSync.stream())
}

package.json 文件是这样的:

{
  "name": "project_name",
  "version": "1.0.0",
  "description": "some description of the project",
  "scripts": {},
  "keywords": ["keyword_1", "keyword_2", "keyword_3"],
  "author": "project_author",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.16.0",
    "@babel/eslint-parser": "^7.16.3",
    "@babel/preset-env": "^7.16.4",
    "@babel/register": "^7.16.0",
    "browser-sync": "^2.27.7",
    "eslint": "^8.2.0",
    "eslint-config-airbnb-base": "^15.0.0",
    "eslint-plugin-import": "^2.25.3",
    "gulp": "^4.0.2",
    "gulp-babel": "^8.0.0",
    "gulp-file-include": "^2.3.0",
    "gulp-notify": "^4.0.0",
    "gulp-rename": "^2.0.0",
    "gulp-uglify-es": "^3.0.0"
  }
}

.babelrc 文件如下所示:

{
  "presets": ["@babel/preset-env"]
}

似乎一切都应用了所需的东西。
如果您能提供帮助,我将不胜感激。
整个项目都因为这个错误而卡住了……
建议不使用就解决问题Webpack:)

4

1 回答 1

1

似乎您可能缺少将代码转换为浏览器兼容的构建步骤。该require方法在浏览器中不可用。

您必须使用一种工具来转换您的代码,以便它可以在浏览器中运行。一个这样的工具是Browserify,另一个是 rollup ,而且可能还有更多。一般来说,这些工具将依赖源与您的应用程序代码捆绑在一起,这允许将 require 语句转换为浏览器可以理解的其他模式。

你可以这样想(例子被简化了):

你写的代码

// main.js
const stringify = require('stringify')

alert(stringify({ error: "No authorization" })

node_modules 中的依赖源

// node_modules/stringify/index.js
function stringify(obj) {
  return JSON.stringify(obj);
}

expost.default = stringify

捆绑结果

// dist/main.js
function stringify(obj) {
  return JSON.stringify(obj);
}

alert(stringify({ error: "No authorization" })

Gulp 在其存储库中托管了一个官方的 browserify 使用示例:

'use strict';

var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var log = require('gulplog');
var uglify = require('gulp-uglify');
var reactify = require('reactify');

gulp.task('javascript', function () {
  // set up the browserify instance on a task basis
  var b = browserify({
    entries: './entry.js',
    debug: true,
    // defining transforms here will avoid crashing your stream
    transform: [reactify]
  });

  return b.bundle()
    .pipe(source('app.js', { sourcemaps: true }))
    .pipe(buffer())
        // Add transformation tasks to the pipeline here.
        .pipe(uglify())
        .on('error', log.error)
    .pipe(gulp.dest('./dist/js/', { sourcemaps: '../sourcemaps/' }));
});

Gulp 版本控制:Browserify + Transforms

我试图为您创建一个示例,但很难说对您的项目最有用的 gulp 脚本是什么。我将添加一个示例,但请不要将其视为可供一般使用的修复程序。它试图模仿你当前的 gulp 脚本的行为。例如,从长远来看,您可能需要其他行为,因为此脚本创建的捆绑可能不像其他配置或工具允许的那样优化。

const { dest } = require("gulp"),
  browserify = require("browserify"),
  babelify = require("babelify"),
  glob = require("glob"),
  source = require("vinyl-source-stream"),
  fileinclude = require("gulp-file-include"),
  rename = require("gulp-rename"),
  uglify = require("gulp-uglify-es").default,
  notify = require("gulp-notify"),
  browserSync = require("browser-sync").create(),
  es = require("event-stream");

const changingScripts = (done) => {
  // Define files you want to have as inputs
  var files = ["src/js/main.js", ...glob.sync("src/js/pages/**/*.js")];
  // Bundle each file separately so that file structure is preserved in
  // dist
  var tasks = files.map((file) => {
    return (
      browserify({
        entries: [file],
        debug: true,
        transform: [
          // Apply babel transforms here so that browserify knows how to bundle
          // the files
          babelify.configure({
            presets: ["@babel/preset-env"],
          }),
        ],
      })
        .bundle()
        // Transform the stream content bable bundling returns into a gulp
        // friendly format
        .pipe(source(file))
        // Not sure how fileinclude is used in your project. May be that it
        // doesn't work when it's configured in this way.
        .pipe(fileinclude())
        .pipe(dest("dist/js"))
        .pipe(
          uglify({
            toplevel: true,
          }).on("error", notify.onError())
        )
        .pipe(
          rename({
            extname: ".min.js",
          })
        )
        .pipe(dest("dist/js"))
        .pipe(browserSync.stream())
    );
  });

  return es.merge(tasks).on("end", done);
};

exports.default = changingScripts;

Gulp:使用 Browserify 创建多个包

于 2021-11-20T08:31:21.723 回答