Gulp 无法通过导入连接文件

pzfprimi  于 2022-12-08  发布在  Gulp
关注(0)|答案(1)|浏览(158)

一天了,我不明白为什么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解决问题:)

w1e3prcc

w1e3prcc1#

看起来你可能错过了一个构建步骤,在这个步骤中你需要转换你的代码以使其与浏览器兼容。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

相关问题