Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm using babel with gulp and create a simple DOM library in ES6. But after running and when i'm going to use it, I got the Object.assign is not a function in chrome console.

this is the gulp code

gulp.task('scripts', function() {
    return gulp.src(src + 'js/*.js')
      .pipe(babel())
      .pipe(concat('main.js'))
      .pipe(gulp.dest(dest + 'js'));

this is the class file

class DOM {
    constructor( selector ) {
        var elements = document.querySelectorAll(selector);
        this.length = elements.length;
        Object.assign(this, elements);
const dom = selector => new DOM(selector);

and I'm using it in client side like dom('#elId');

Where is that error coming from? All the code you show is from the gulp (node?) script, but your error if from Chrome. Show the relevant code – Amit Aug 1, 2015 at 17:43 Please, do not use concat on Babel output. JS files are modules, they are not meant to be concatenated together. Use a bundler like browserify w/ babelify so you get the proper module behavior. – loganfsmyth Aug 1, 2015 at 17:58

As I suspect you already know, Google Chrome uses V8, which supports ECMAScript 5th edition. Object.assign is introduced in ECMAScript 6th edition.

In order to use these additions, you need to include the ES6 polyfill provided by Babel:

This will emulate a full ES6 environment. [...]

Available from the browser-polyfill.js file within a babel-core npm release. This needs to be included before all your compiled Babel code. You can either prepend it to your compiled code or include it in a <script> before it.

Just in case anyone else hits the same issue as I did - make sure you include this before any other libraries. Seems obvious in hindsight but took a while to work out where I'd messed up :( – Chris Owens Mar 25, 2019 at 6:59

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.