通过导入连接文件不起作用

Connecting files via import does not work

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

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;

Gulp 任务:

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解决问题:)

您似乎错过了一个构建步骤,在这个步骤中您 运行 将您的代码修改为与浏览器兼容。 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 Version control: 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: Creating multiple bundles with Browserify