Ronan
Ronan

Reputation: 177

Can't make object imports in ES6 modules work with Gulp, Browserify and Babelify

I really enjoy ES6 modules but I'm having a hard time making them fully work with Browserify and enhanced object literals.

I've created a reduced test case to sum up my issue.

Here is the gulpfile:

var gulp = require('gulp');
var babelify = require('babelify');
var browserify = require('browserify');
var buffer = require('vinyl-buffer');
var source = require('vinyl-source-stream');

gulp.task('scripts', function() {
  var b = browserify({
    entries: 'main.js',
    debug: true
  })
  .transform(babelify)

  return b.bundle()
  .pipe(source('bundle.js'))
  .pipe(buffer())
  .pipe(gulp.dest('./'));
});

gulp.task('default', ['scripts']);

Its goal is to transform ES6 modules with Browserify and transpile ES6 to ES5.

Now, I have no issue with basic imports, but I can't make it work with object imports. Let's say I have those two files:

utils.js

let utils = {
  sayHi() {
    console.log('hi');
  }
}

main.js

import utils from './utils';

utils.sayHi();

This will fire an error: Uncaught TypeError: _utils2.default.sayHi is not a function

And at this point I can't find any decent workaround. Any help would be greatly appreciated!

Upvotes: 0

Views: 2141

Answers (2)

Felix Kling
Felix Kling

Reputation: 816302

You are not exporting anything from utils.js, so there is nothing you could import.

If you want to be able to import the object as written, you have to make it the default export:

export default utils;

Upvotes: 3

marcel
marcel

Reputation: 3149

Try this:

// utils.js
export default utils = { ... }

// main.js
import utils from './utils';

utils.sayHi();

If you don't export utils as default, you have to change the import to this:

import { utils } from './utils';

Upvotes: 1

Related Questions