如何使用babel和webpack将导出的函数公开到全局范围 [英] How expose a exported function into global scope with babel and webpack

查看:271
本文介绍了如何使用babel和webpack将导出的函数公开到全局范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用webpack和babel编译代码,以便导出的函数在全局范围内可用.

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

例如:

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

应该在window.test()下可用.

当我刚运行babel -d时,我得到了期望的结果:

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');
}

但是webpack的输出看起来像这样:

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
}]);

结束test函数在全局范围内不可用.

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

推荐答案

签出: https://github.com/webpack/docs/wiki/library- and-externals#examples

通过将 library 输出属性设置为要包装全局变量的任何名称,您可以调用: YourLibrary .test();.

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'
    }

这篇关于如何使用babel和webpack将导出的函数公开到全局范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆