Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 import module with Gulp

I am trying to import my ES6 module into a file and running Gulp to concat and minify the file. I'm running into a ReferenceError: require is not defined at all.js(transpiled) line no 3. I have transpiled the code using gulp-babel.

My js files are:

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;
like image 996
Neil Avatar asked Dec 04 '17 11:12

Neil


3 Answers

You would need a bundler like Webpack or Browserify in order to use ES6 imports. Babel is only capable of compiling ES6 code to ES5 (native JS).

Both Webpack and Browserify have made recipes for gulp:

  • https://webpack.js.org/guides/integrations/#gulp
  • https://github.com/gulpjs/gulp/tree/master/docs/recipes

Hope this helps.

like image 122
JasonK Avatar answered Nov 08 '22 12:11

JasonK


Rollup is a good bundler for handling ES6 modules. It has native ES6 module support built in so it doesn't need to use Babel unlike Browserify.

Here is a Gulp 4 config that uses Rollup:

// 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'));
like image 27
Daniel Tonon Avatar answered Nov 08 '22 12:11

Daniel Tonon


If the above solutions don't work for you, try gulp-include.

It uses directives similar to sprockets or snockets. A directive is a comment in your files that gulp-include recognizes as a command.

Usage

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
like image 5
myk Avatar answered Nov 08 '22 13:11

myk