Using Babel to convert ES6 modules to ES5 AMD modu

2019-06-24 03:28发布

问题:

I hope someone can help.

I'm using grunt-babel to convert my ES6 module code to ES5 AMD module code. Here's my ES6 code:

multiply.js

export default function (x,y) {
    return x * y;
};

square.js

import multiply from 'multiply';
export default function (x) {
   return multiply(x,x);
};

app.js

import square from 'square';

var myValue = square(2);
console.log(myValue);

As you can see, all I'm doing is creating a module 'multiply', importing that into another module 'square', and then finally using 'square' in my main js file. The above 3 files then gets converted to the following:

multiply.js

define("multiply", ["exports", "module"], function (exports, module) {
    module.exports = function (x, y) {
        return x * y;
    };
});

square.js

define("square", ["exports", "module", "multiply"], function (exports, module, _resourcesJsEs6moduleExampleMultiply) {
    var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };

    var multiply = _interopRequire(_resourcesJsEs6moduleExampleMultiply);

    module.exports = function (x) {
        return multiply(x, x);
    };
});

app.js

define("app", ["exports", "square"], function (exports, _resourcesJsEs6moduleExampleSquare) {
    var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };

    var square = _interopRequire(_resourcesJsEs6moduleExampleSquare);

    var myValue = square(2);
    console.log(myValue);
});

The problem I have is that I expected the 'app.js' file to be converted to something more like this:

requirejs(['square'],
    function (square) {
        var myValue = square(2);
        console.log(myValue);
    }
);

In my gruntfile.js my config is pretty simple:

options: {
    moduleIds: true,
    modules: 'amd',
    blacklist: ['strict']
}

Am I doing something wrong?

回答1:

After some further digging I finally realised where I went wrong.

In my current stack I'm forced to use Almond, instead of RequireJS. Because of this, Almond expects there to be a file to initialise the modules, hence why I was expecting Babel to generate one for me. But as it turns out, the code generated by Babel will work fine within RequireJS, but for it to work with Almond, I need to create a seperate es5 js file, just to initialise the files generated by Babel.

Something like this:

requirejs(['app'],
    function (app) {
        app();
    }
);