Using Babel to convert ES6 modules to ES5 AMD modules, not working as expected

二次信任 提交于 2019-12-10 15:21:51

问题


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();
    }
);


来源:https://stackoverflow.com/questions/28963263/using-babel-to-convert-es6-modules-to-es5-amd-modules-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!