javascript - 使用 Babel 将 ES6 模块转换为 ES5 AMD 模块,未按预期工作

标签 javascript gruntjs amd ecmascript-6 babeljs

我希望有人能提供帮助。

我正在使用 grunt-babel 将我的 ES6 模块代码转换为 ES5 AMD 模块代码。这是我的 ES6 代码:

乘法

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

方形.js

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

应用程序.js

import square from 'square';

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

如您所见,我所做的只是创建一个模块“multiply”,将其导入另一个模块“square”,最后在我的主 js 文件中使用“square”。上面的 3 个文件然后被转换为以下内容:

乘法

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

方形.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);
    };
});

应用程序.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);
});

我遇到的问题是我希望将“app.js”文件转换为更像这样的文件:

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

在我的 gruntfile.js 中,我的配置非常简单:

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

我做错了什么吗?

最佳答案

经过进一步挖掘,我终于意识到哪里出了问题。

在我当前的堆栈中,我被迫使用 Almond,而不是 RequireJS。正因为如此,Almond 希望有一个文件来初始化模块,因此我希望 Babel 为我生成一个文件。但事实证明,Babel 生成的代码在 RequireJS 中可以正常工作,但要使其与 Almond 一起工作,我需要创建一个单独的 es5 js 文件,以初始化 Babel 生成的文件。

像这样:

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

关于javascript - 使用 Babel 将 ES6 模块转换为 ES5 AMD 模块,未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28963263/

相关文章:

javascript - Bootstrap选项卡刷新页面

RequireJS - 当在define()中指定模块id时

javascript - 允许模块与 AMD/CommonJs 或脚本标签一起工作的包装器?

node.js - 咕噜声 : Running multiple mocha tests with different environments/processes

javascript - Grunt 首先连接目录递归文件

javascript - requirejs blueimp fileuploader 只加载 min.js 文件而不加载其他文件

javascript - 如何通过更改单选按钮来更改桨宽度?

javascript - JSONP 没有按预期在 AngularJS 中工作

javascript - 用 X 替换内部信用卡号的正则表达式?

javascript - 将 haml 文件转换为 html 时复制整个文件夹结构(使用 grunt)