1

If I have an ES6 JS file (test.js) ...

export default function() {
  let foo = "test"
  return foo
}

With Babel, is it possible to transpile and call it in an index.html file

<script src="js/text-min.js"></script>

And start using the function without needing to import it into another js file? For Ex. the next script tag after would have the following code. This is in use with Webpack --

<script>
  var bar = new foo();
  console.log(bar);
</script>
4

3 回答 3

0

上述代码的转译版本如下所示,

"use strict";

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

  exports.default = function () {
     var foo = "test";
     return foo;
  };

如您所见,它添加了一个属性来导出名为 __esModule 的对象。没有其他的。所以你没有办法在不使用 import 或 require 的情况下包含这个默认函数。

于 2016-10-13T20:32:04.780 回答
0

您实际上正在寻找的是一个全局变量(这可能不是一个好主意)。例如:

模块一:

import {foo} from 'foo'; // still an ES6 module, just no export

// global variable 'bar'
window.bar = (...args) => foo(...args) + 6;

然后在模块 2 中:

bar(1, 3, 5);

请注意,这会破坏使用模块的全部意义,并且应该非常谨慎地使用。

于 2016-10-13T20:41:30.923 回答
0

好的,我通过使用 Webpack 提供输出变量解决了这个问题。与此相关的好文章——http: //siawyoung.com/coding/javascript/exporting-es6-modules-as-single-scripts-with-webpack.html

于 2016-10-13T23:09:48.747 回答