带有Gulp的ES6导入模块

时间:2017-12-04 11:34:11

标签: javascript gulp gulp-babel

我正在尝试将我的ES6模块导入文件并运行Gulp以连接并缩小文件。我遇到了 ReferenceError:在all.js(已编译)第3行中未定义require。 我用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(transpiled):

'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;

3 个答案:

答案 0 :(得分:7)

您需要使用WebpackBrowserify这样的捆绑器才能使用ES6导入。 Babel只能将ES6代码编译为ES5(原生JS)。

Webpack和Browserify都为gulp制作了食谱:

希望这有帮助。

答案 1 :(得分:1)

如果上述解决方案不适合您,请尝试gulp-include

它使用类似于链轮或门襟的指令。指令是文件中的注释,而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

答案 2 :(得分:0)

要使gulp与ES6导入配合使用,您需要做三件事:

  1. gulpfile.ts / gulpfile.js重命名为gulpfile.babel.ts / gulpfile.babel.js

  2. 运行此命令:

npm i @babel/preset-env @babel/register -D
  1. 在项目的根文件夹中添加一个.babelrc文件,其中包含以下代码:
{
  "presets": [
    "@babel/preset-env"
  ]
}

您现在应该可以在Gulp文件中使用ES6导入。