Search code examples
javascriptecmascript-6babeljsamdjs-amd

object doesn't support this action new x() after babel transform


I am currently converting a bunch of JavaScript modules to ECMAScript 6 classes. We are using require.js for the AMD loader and were manually writing the define([], ...) logic.

We are using Babel to transpile the ES 6 classes back to ES 5 defined modules. My bablerc file looks like this:

{
"presets": ["es2015"],
"plugins": ["transform-es2015-modules-amd"]
}

A simple class looks like this

import x from "dev/x"
import ko from "knockout"
import z from "dev/z"

export class y extends x {
...
}

The output looks MOSTLY right:

define(["exports","dev/x", "knockout", "dev/z"], function(x, knockout, z){

Object.defineProperty(exports,"__esModule",{value: true});

// Bunch of generated crap
var y = exports.y = function(_x)...(_x2.default);
}

So when I try to do:

var foo = new y();

I get an "Object doesn't support this action" JavaScript exception.

I have tried to change the generated code (which I don't want to do) to read:

var y = exports = function(_x)...(_x2.default);

But that didn't do anything. However when I change that line to this:

return function(_x)...(_x2.default);

or add this line:

var y = exports = function(_x)...(_x2.default);
return y;

Everything works like it should. I do not want to have to modify the generated file every time we make a change, I just want babel to do it's thing and be right! What am I missing here?

UPDATE: I am using system.js part of the Druandal libraries (durandaljs.com) that wraps the calls to require by passing a function called aquire a module ID and it loads it up. So I do a call like this:

system.acquire(moduleNameAndPath).then(function acquiredModuleFunc(acquiredModule) {
    if (acquiredModule !== null || acquiredModule !== undefined){
        var item = new acquiredModule(); // Object doesn't support here...
    }
}

We are using this to introduce a pseudo polymorphic behavior when constructing view models that a view is bound to.


Solution

  • You are exporting the constructor under the name y. In your import (acquire) you seem to try using new on the module object itself. Instead, try

    system.acquire(moduleNameAndPath).then(function(acquiredModule) {
        var Y = acquiredModule.y;
        var item = new Y();
    });