简体   繁体   中英

ES6 Exporting and Importing a Function

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>

The transpiled version of the above code produces like this,

"use strict";

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

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

As you can see, it add a property to export object with the name __esModule . Nothing else. So you don't have a way to include this default function without using import or require.

What you are actually looking for is a global variable (which is probably not a great idea). For instance:

Module 1:

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

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

Then in Module 2:

bar(1, 3, 5);

Note that this defeats the entire point of using modules and should be used very sparingly.

Okay so I solved this issue by providing an output var using Webpack. Great article that speaks to this -- http://siawyoung.com/coding/javascript/exporting-es6-modules-as-single-scripts-with-webpack.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM