【问题标题】:(How) can I use System.import in babel along with require.js?(如何)我可以在 babel 中使用 System.import 和 require.js 吗?
【发布时间】:2015-12-28 23:17:57
【问题描述】:

我正在使用新的 ES6 功能和 Babel。我通过 require.js(转译成 AMD)成功地使用了模块导出/导入功能,但是实验性的 module loader 没有不想工作。这是我的代码和配置:

front-app/tst.js 的摘录

import {tstimp as functocall} from "front-app/tstimp.js";

...

/**
 * LOADING MODULES DYNAMICALLY
 */
System.import('front-app/tst_dyn_mod')
    .then(some_module => {
        console('using the module!');
        some_module.sayHello();
    })
    .catch(error => {
        console.log('error!');
        console.log(error);
    });

我的.babelrc 看起来像这样:

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

我导入的脚本是这些,按顺序:

<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
        <script src="node_modules/babel-polyfill/dist/polyfill.min.js"></script>
        <script data-main="front-app/tst" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.8/require.min.js"></script>
        <script src="node_modules/es6-module-loader/dist/es6-module-loader.js"></script>
    </head>
    <body></body>
</html>

不幸的是,我使用 firefox 得到以下错误:

error! tst.js:695:9
Error: a is undefined
    Error loading http://localhost/es6r1/front-app/tst_dyn_mod

a 是什么?我错过了什么吗?请记住,我的代码已转译为 AMD,但 System 应该保留在转译代码中(并且它就在那里)。 polyfill 应该完成这项肮脏的工作,对吧?

【问题讨论】:

    标签: babeljs systemjs es6-module-loader


    【解决方案1】:

    感谢这个插件:https://www.npmjs.com/package/babel-plugin-system-import (@ 987654324@)。这是我的 .babelrc 的摘录:

    …
    "plugins": [
      "system-import-transformer",
      {
        "modules": "common"
      }
    ]
    …
    

    设置 amd 而不是文档中指示的常见设置应该可以为您解决问题。

    这个小插件的唯一限制是,你应该得到一个像System.import("plainString")这样的纯字符串模块名称,而不是计算出来的(也不是与+的字符串连接,也不是新的ES6 template literal,也不是变量名)。它似乎与that line of code 相关联。

    如果可以的话,我会尝试 PR 修复该限制。

    【讨论】:

      【解决方案2】:

      只是对此的更新,https://github.com/thgreasi/babel-plugin-system-import-transformer 支持非字符串参数。请确保不要使用更新的别名包。

      【讨论】:

        猜你喜欢
        • 2015-08-23
        • 2015-08-26
        • 2019-08-03
        • 2017-11-08
        • 2021-06-11
        • 1970-01-01
        • 2017-08-04
        • 2020-03-01
        • 1970-01-01
        相关资源
        最近更新 更多