使用Gulp导入ES6模块

28

我正试图将我的ES6模块导入文件并运行Gulp来连接和压缩该文件。我遇到了一个引用错误:require未定义,在all.js(转译后)的第3行

我已经使用gulp-babel将代码转译过了。

我的js文件是:

cart.js:

class Cart{
  constructor(){
    this.cart = [];
    this.items = items = [{
        id: 1,
        name: 'Dove Soap',
        price: 39.99
    },{
        id: 2,
        name: 'Axe Deo',
        price: 99.99
    }];
  }


  getItems(){
    return this.items;
  }


}

export {Cart};

app.js:

import {Cart} from 'cart.js';

let cart = new Cart();

console.log(cart.getItems());

gulpfile.js:

"use strict";

let gulp = require('gulp');
let jshint = require('gulp-jshint');
let concat = require('gulp-concat');
let uglify = require('gulp-uglify');
let rename = require('gulp-rename');
let babel = require('gulp-babel');


// Lint Task
gulp.task('lint', function() {
    return gulp.src('js/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});


// Concatenate & Minify JS
gulp.task('scripts', function() {
    return gulp.src('js/*.js')
        .pipe(babel({
            presets: ['env']
        }))
        .pipe(concat('all.js'))
        .pipe(gulp.dest('dist'))
        .pipe(rename('all.min.js'))
        .pipe(uglify().on('error', function(e){
          console.dir(e);
        }))
        .pipe(gulp.dest('dist/js'));
});

// Default Task
gulp.task('default', ['lint','scripts']);

app.js(编译后):

'use strict';

var _cart = require('cart.js'); //Uncaught ReferenceError: require is not defined

var cart = new _cart.Cart();

console.log(cart.getItems());
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Cart = function () {
  function Cart() {
    _classCallCheck(this, Cart);

    this.cart = [];
    this.items = items = [{
      id: 1,
      name: 'Dove Soap',
      price: 39.99
    }, {
      id: 2,
      name: 'Axe Deo',
      price: 99.99
    }];
  }

  _createClass(Cart, [{
    key: 'getItems',
    value: function getItems() {
      return this.items;
    }
  }]);

  return Cart;
}();

exports.Cart = Cart;

我正在尝试在浏览器中运行app.js,所以如果我没错的话,require('something')是不会起作用的。我需要使用browserify吗? - Neil
你需要在babel之后运行webpack-stream。安装过程并不是很有趣,我放弃了尝试创建一个示例。gulp-webpack是另一个包,但我认为它已经不再维护了。 - Mika Sundland
FYI,browserify 只有在正确包装后才能与 gulp 一起使用。这里是一个基本用法示例的配方 - Patrick Roberts
2
你能分享一下你使用webpack/browserify的最终配置吗?我在我的项目中设置它们时遇到了困难,而且我的gulp配置与你的类似。 - muuvmuuv
3个回答

24

Rollup是一个处理ES6模块的好打包工具。它内置了本地的ES6模块支持,因此不像Browserify一样需要使用Babel。

这里是一个使用Rollup的Gulp 4配置:

// gulp.js file in the root folder

var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var rollup = require('@rollup/stream');

// *Optional* Depends on what JS features you want vs what browsers you need to support
// *Not needed* for basic ES6 module import syntax support
var babel = require('@rollup/plugin-babel');

// Add support for require() syntax
var commonjs = require('@rollup/plugin-commonjs');

// Add support for importing from node_modules folder like import x from 'module-name'
var nodeResolve = require('@rollup/plugin-node-resolve');

// Cache needs to be initialized outside of the Gulp task 
var cache;

gulp.task('js', function() {
  return rollup({
      // Point to the entry file
      input: './app.js',

      // Apply plugins
      plugins: [babel(), commonjs(), nodeResolve()],

      // Use cache for better performance
      cache: cache,

      // Note: these options are placed at the root level in older versions of Rollup
      output: {

        // Output bundle is intended for use in browsers
        // (iife = "Immediately Invoked Function Expression")
        format: 'iife',

        // Show source code when debugging in browser
        sourcemap: true

      }
    })
    .on('bundle', function(bundle) {
      // Update cache data after every bundle is created
      cache = bundle;
    })
    // Name of the output file.
    .pipe(source('bundle.js'))
    .pipe(buffer())

    // The use of sourcemaps here might not be necessary, 
    // Gulp 4 has some native sourcemap support built in
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(sourcemaps.write('.'))
 
    // Where to send the output file
    .pipe(gulp.dest('./build/js'));
});
 
gulp.task('js:watch', function(done){
  gulp.watch(['./source/**/*.js'], gulp.series('js'));
  done();
})
 
gulp.task('default', gulp.series('js', 'js:watch'));

我曾经认为在这里找到了解决方案,但是我遇到了几个不同的错误 https://github.com/rollup/plugins/issues/485 - Tristanisginger
错误:找不到模块“@rollup/stream”。但是Rollup已经设置为开发依赖项。 - Woww
npm install @rollup/stream - Daniel Tonon

23

1
我从未能够让Browserify与Gulp配合工作。然而Webpack第一次尝试就成功了!感谢你节省了我数小时的时间。 - Jan Werkhoven

6
如果以上解决方案对您不起作用,请尝试使用gulp-include

它使用类似于sprockets或snockets的指令。指令是您文件中的注释,gulp-include将其识别为命令。

用法

gulpfile.js:

const gulp = require('gulp')
const include = require('gulp-include')
 
exports.scripts = function (done) {
  gulp.src('source/js/entry.js')
    .pipe(include())
      .on('error', console.log)
    .pipe(gulp.dest('dist/js'))
}

app.js:

//=require ./js/cart.js
//=include ./js/cart.js

那正是我真正想要的! - Amir2mi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接