Using ES6 for importing modules with Gulp

I'm having trouble bringing in my ES6 module into a file and using Gulp to concatenate and minimize it. When I try to run it, I keep getting a ReferenceError: require is not defined at all.js(transpiled) line no 3. I've already transpiled the code with gulp-babel.

Here are my js files:

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;

Answer №1

Rollup is a fantastic tool for bundling ES6 modules efficiently. Unlike Browserify, Rollup comes with built-in support for ES6 modules, eliminating the need for additional plugins like Babel.

Below is a configuration example using Gulp 4 and 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* Depending on required JS features and browser compatibility
// *Not necessary* for basic ES6 module import syntax
var babel = require('@rollup/plugin-babel');

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

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

// Initialize cache outside of the Gulp task 
var cache;

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

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

      // Utilize cache for better performance
      cache: cache,

      output: {
        format: 'iife', // Output bundle for browsers (Immediately Invoked Function Expression)
        sourcemap: true // Enable source mapping for debugging
      }
    })
    .on('bundle', function(bundle) {
      // Update cache after each bundle creation
      cache = bundle;
    })
    .pipe(source('bundle.js')) // Name of the output file
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true})) // Initiate sourcemaps
    .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('./build/js')); // Output destination
});
 
gulp.task('js:watch', function(done){
  gulp.watch(['./source/**/*.js'], gulp.series('js'));
  done();
})
 
gulp.task('default', gulp.series('js', 'js:watch'));

Answer №3

If you're still experiencing issues with the solutions mentioned above, consider giving gulp-include a try.

This package utilizes directives that are reminiscent of sprockets or snockets. Directives in your files serve as commands that gulp-include can recognize.

How to Use

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to creating a search-enabled dropdown menu

Recently, I created a dropdown menu using Bootstrap. The code I used can be found here: http://getbootstrap.com/docs/4.0/components/dropdowns/ <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownM ...

Discover the current style being applied using JavaScript

After taking a look at this particular post on Stack Overflow about How to retrieve the background color of an element using javascript? I discovered that by using div.style.color You can access the color applied to the div element. However, it seems ...

Using jQuery to duplicate elements by copying and pasting

I am facing a scenario where I need to dynamically create and manipulate a div element in my web application. The process involves appending the newly created div to another container upon clicking a button, followed by triggering a series of functions on ...

Trouble with defining variables in EJS

Recently delving into the world of node development, I encountered an issue with my EJS template not rendering basic data. I have two controllers - one for general pages like home/about/contact and another specifically for posts. When navigating to /posts ...

Is there a way to prevent the installation of unnecessary node modules that are not included in my package.json file?

"dependencies": { "jquery": "^2.2.3", "normalize.css": "^4.1.1" }, "devDependencies": { "browser-sync": "^2.12.3" } } My package.json file contains specific dependencies, but when I delete the node_modules folder and execute npm install, it unexpected ...

JavaScript - The left dropdown menu stubbornly remains visible when clicked in white space, unlike the right dropdown which disappears as expected. Puzzled by this inconsistency

Whenever I click on the selection criteria box, a dropdown menu appears. Clicking on the white space or the data table button makes the drop-down menu disappear, which is good. However, when I perform the same action for 'choose data table,' the ...

Is there a way to bypass the final function call when using Express Middleware?

In my Node.js project using express, I have a function inside a get route... The function currently includes a simple caching functionality that I coded myself. It queries data from an MSSQL Database and returns it using res.json(data). However, I want to ...

There was an issue attempting to access the 'host' property as it was undefined

I am facing an issue while trying to establish a connection between my application and MongoDB. The error message 'Error: Cannot read properties of undefined (reading 'host')' keeps popping up, and I'm unable to pinpoint the root c ...

Replace all existing content on the webpage with an exciting Unity game upon clicking

In an interesting experiment, I am trying to hide a secret href that, once clicked, has the power to wipe out everything on the page, leaving it temporarily blank before replacing it with a captivating Unity game that takes over the entire page. Let me sh ...

Tips for resolving the "Page Not Found" error in your NextJs application

I am organizing my files in the following structure src/ ├── app/ │ ├── pages/ │ │ ├── authentication/ │ │ │ ├── SignUp/ │ │ │ │ └── page.tsx │ │ │ └── SignIn/ │ ...

CoffeeScript and Node.js: Encountering an Unexpected ">" Token (Arrow Function)

After attempting to execute the following coffeescript, the issue arises: request = require('request') request('http://google.com', (error, response, body) -> if not error and response.statusCode is 200 console.log(body ...

When the input field is clicked, the file:/// URL is sent

Currently, my HTML page contains a form that includes an input field for URLs. Ideally, upon typing in the URL and clicking the button, I intend to be redirected to that website. However, the issue lies in the fact that instead of redirecting me to the p ...

How can you protect against XSS when using React server-side rendering and window.initialState?

When passing my initial state to React, I do it like this: window.__INITIAL_STATE__= ${JSON.stringify(initialState)} I have not implemented any protection against XSS. For example, if user-submitted content contains the following string: "<script>* ...

Passing the value of the selected calendar date to the controller

How can I pass the value generated by this calendar_date_select to the controller? Any suggestions on how to modify the onchange code? <%= calendar_date_select_tag "meeting_date_1", @time, :embedded => true, :time => true, :minut ...

Display a message stating "No data available" using HighCharts Angular when the data series is empty

My Angular app utilizes Highchart for data visualization. One of the requirements is to display a message within the Highchart if the API returns an empty data set. I attempted a solution, but unfortunately, the message does not appear in the Highchart a ...

Is it possible that attaching the click event directly to the ID is effective while attaching it to the childnode is not working

Can anyone help me with a problem I'm having? When I try to target a specific element by accessing its child nodes, the click event doesn't work. However, if I use getElementById and then attach the click event through that method, it works. Idea ...

Trigger the function upon successful completion of Stripe Checkout

I have a requirement in my Nodejs/Express API to execute a series of confirmation code once the checkout process is successfully completed in Stripe by the client. Below is the checkout function responsible for handling the checkout phase: // Checkout con ...

Submitting data twice through AJAX POST requests

Using a PHP file called via AJAX to insert data into MySQL. Prior to the insert statement, the PHP code runs a select query to check for duplicate records and then proceeds with the insert statement. Problem: When calling the PHP file from AJAX, it gets ...

Typescript: Error encountered. Invalid input: Non-string value provided to `ts.resolveTypeReferenceDirective`

A while back, I developed an npm command line application that was working perfectly fine. However, after a recent update due to changes in TypeScript versions over time, I encountered an error when trying to run the package. The error message I received w ...

After updating Angular Material, the alert dialogs are now transforming into a large dark region

Recently, I encountered an issue while attempting to upgrade my old version of angular-material (v0.9.0) to a newer one. The reason behind this upgrade was the necessity to utilize the new htmlContent for an alert using $mdDialog. However, after replacing ...