21

How can I compile my code with webpack and babel so that the exported function is available in the global scope.

So for example:

export function test(){console.log('test')}

Should be available under window.test().

When I just run babel -d I got what I expect:

'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports.test = test;

function test() {
  console.log('test');
}

but the webpack output looks like this:

!function(e) {
  function t(r) {
    if (o[r])return o[r].exports;
    var n = o[r] = {exports: {}, id: r, loaded: !1};
    return e[r].call(n.exports, n, n.exports, t), n.loaded = !0, n.exports
  }

  var o = {};
  return t.m = e, t.c = o, t.p = "", t(0)
}([function(e, t) {
  "use strict";
  function o() {
    console.log("test")
  }

  Object.defineProperty(t, "__esModule", {value: !0}), t.test = o
}]);

end the test function is not available in the global scope.

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297

2 Answers2

13

You can easily set a property on the global window object. This will expose your object to the global scope.

function test() {
  console.log('test');
}

window.test = test;

If you are developing a piece of code that does not represent a library but just some operations or functionalities to operate in global scope, I would prefer this method over to setting the library output property as mentioned in the accepted answer.

ILCAI
  • 1,164
  • 2
  • 15
  • 35
10

check out: https://github.com/webpack/docs/wiki/library-and-externals#examples

By setting the library output property to whatever name you want to wrap your globals would allow you to then call: YourLibrary.test();

module.exports = {
    entry: ['./_js/script.js'],
    output: {
       library: 'YourLibrary',
        path: __dirname,
        filename: './build/script.js'
    }
Sebastian
  • 1,076
  • 9
  • 24
glued
  • 2,579
  • 1
  • 25
  • 40
  • 9
    but how to just export one function – Jiang YD Jul 13 '16 at 15:38
  • in the example above do you mean just calling `YourLibrary()` as a function, i'm not sure if that is possible. You can however only expose/export a single function, for example, export function `foo(){...` then call `YourLibrary.foo()` – glued Jul 14 '16 at 05:15
  • 2
    yes, but I need call functions in other module exported in `YourLibrary.foo()` – Jiang YD Jul 18 '16 at 10:59