gulp 压缩js 后 浏览器无法运行 require is not defined?

Uncaught ReferenceError: require is not defined
gulp 压缩后希望可以在浏览器运行,这种要怎么修改呢?
gulpfile.js 配置

const gulp = require('gulp');//引入gulp  
const htmlMin = require('gulp-htmlmin');//引入html压缩模块  
const autoprefixer = require('gulp-autoprefixer');
const cleanCss = require('gulp-clean-css') //引入css压缩模块
const babel = require('gulp-babel'), //引入es6转es5模块
    uglify = require('gulp-uglify') //引入js压缩模块
const connect = require('gulp-connect');
const webserver = require('gulp-webserver');
const proxy = require('http-proxy-middleware');
const sass = require('gulp-sass')(require('sass'));

// 方便路径管理
const path = {
    html: {
        src: 'src/**/*.html',
        dest: 'dist'
    },
    css: {
        src: 'src/**/*.css',
        dest: 'dist'
    },
    js: {
        src: 'src/**/*.js',
        dest: 'dist'
    },
    scss: {
        src: 'src/**/*.scss',
        dest: 'dist'
    }
}

/** 
 * 创建任务,并命名任务名
 * 一个*表示所有文件,两个*表示所有目录
 */
const htmlCompress = () => {
    return gulp.src(path.html.src)
        .pipe(htmlMin({
            removeComments: true,//清除HTML注释
            collapseWhitespace: true,//压缩HTML
            collapseBooleanAttributes: true,//压缩布尔属性的值
            removeEmptyAttributes: true,//删除所有空格作属性值
            removeScriptTypeAttributes: false,//删除<script>的type="text/javascript"
            removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"  
            minifyJS: true,//压缩页面JS
            minifyCSS: true //压缩页面css
        })).pipe(gulp.dest(path.html.dest)) //指定压缩文件放置的目录 
}

const scssCompile = () => {
    return gulp.src(path.scss.src)
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest(path.scss.dest));
}
const cssCompress = () => {
    return gulp.src(path.css.src)
        .pipe(autoprefixer({
            cascade: false
        }))
        .pipe(cleanCss())
        .pipe(gulp.dest(path.css.dest))
}

const jsCompress = () => {
    return gulp.src(path.js.src)
        .pipe(babel({
            presets: ['@babel/env'] //es6转es5
        }))
        .pipe(uglify()) //执行压缩
        .pipe(gulp.dest(path.js.dest))
}

const watch = () => {//监听文件,文件改变执行对应的任务
    gulp.watch(path.html.src, htmlCompress)
    gulp.watch(path.scss.src, scssCompile)
    gulp.watch(path.html.src, cssCompress)
    gulp.watch(path.js.src, jsCompress)
}

// const server = () => {
//     // 创建服务器
//     connect.server({
//         root: 'dist',//根目录
//         port: '2000',//端口号  
//         livereload: true //服务器热更新
//     })
// }

const createServer = () => {
    return gulp.src('./dist')
        .pipe(webserver({ //创建服务器
            port: '3000', //端口号
            host: 'xx.xx.xx.xxx',
            open: '/dark-rankings.html', //默认打开路径
            livereload: true, //热更新
            middleware: [
                proxy.createProxyMiddleware('/api', { //创建反向代理,请求已 /api 开头就使用target的服务器
                    target: 'http://xxx.xxx.xxx.xx',
                    changeOrigin: true
                })
            ]
        })).pipe(connect.reload())
}

/* 以对象形式导出 */
/* 同时运行多个任务 */
module.exports.default = gulp.series(gulp.parallel(htmlCompress, scssCompile, cssCompress, jsCompress, watch, createServer));
阅读 2.2k
1 个回答

推荐你用 Browserify。用 Browserify 和 Gulp 的示例配置:

先安装:

npm install --save-dev vinyl-source-stream vinyl-buffer browserify babelify
const gulp = require('gulp');
const htmlMin = require('gulp-htmlmin');
const autoprefixer = require('gulp-autoprefixer');
const cleanCss = require('gulp-clean-css');
const browserify = require('browserify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');
const uglify = require('gulp-uglify');
const connect = require('gulp-connect');
const webserver = require('gulp-webserver');
const proxy = require('http-proxy-middleware');
const sass = require('gulp-sass')(require('sass'));

const path = {
  html: {
    src: 'src/**/*.html',
    dest: 'dist'
  },
  css: {
    src: 'src/**/*.css',
    dest: 'dist'
  },
  js: {
    src: 'src/**/*.js',
    dest: 'dist'
  },
  scss: {
    src: 'src/**/*.scss',
    dest: 'dist'
  }
};

const htmlCompress = () => {
  return gulp.src(path.html.src)
    .pipe(htmlMin({
      removeComments: true,
      collapseWhitespace: true,
      collapseBooleanAttributes: true,
      removeEmptyAttributes: true,
      removeScriptTypeAttributes: false,
      removeStyleLinkTypeAttributes: true,
      minifyJS: true,
      minifyCSS: true
    }))
    .pipe(gulp.dest(path.html.dest));
};

const scssCompile = () => {
  return gulp.src(path.scss.src)
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest(path.scss.dest));
};

const cssCompress = () => {
  return gulp.src(path.css.src)
    .pipe(autoprefixer({
      cascade: false
    }))
    .pipe(cleanCss())
    .pipe(gulp.dest(path.css.dest));
};

const jsCompress = () => {
  return browserify({
      entries: './src/js/main.js', // 入口文件路径,根据你的实际情况进行修改
      debug: true
    })
    .transform(babelify, {
      presets: ['@babel/preset-env']
    })
    .bundle()
    .pipe(source('output.js'))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest(path.js.dest));
};

const watch = () => {
  gulp.watch(path.html.src, htmlCompress);
  gulp.watch(path.scss.src, scssCompile);
  gulp.watch(path.css.src, cssCompress);
  gulp.watch(path.js.src, jsCompress);
};

const createServer = () => {
  return gulp.src('./dist')
    .pipe(webserver({
      port: '3000',
      host: 'xx.xx.xx.xxx',
      open: '/dark-rankings.html',
      livereload: true,
      middleware: [
        proxy.createProxyMiddleware('/api', {
          target: 'http://xxx.xxx.xxx.xx',
          changeOrigin: true
        })
      ]
    }))
    .pipe(connect.reload());
};

module.exports.default = gulp.series(
  gulp.parallel(htmlCompress, scssCompile, cssCompress, jsCompress),
  gulp.parallel(watch, createServer)
);

主要修改的部分加了 browserify 和 vinyl-source-stream :

const browserify = require('browserify');
const source = require('vinyl-source-stream');
const buffer = require('vinyl-buffer');

修改了jsCompress 任务的内容:

const jsCompress = () => {
  return browserify({
      entries: './src/js/main.js', // 入口文件路径,
      debug: true
    })
    .transform(babelify, {
      presets: ['@babel/preset-env']
    })
    .bundle()
    .pipe(source('output.js'))
    .pipe(buffer())
    .pipe(uglify())
    .pipe(gulp.dest(path.js.dest));
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进