简体   繁体   English

我可以阻止babeljs将函数转换为本地var吗?

[英]Can I stop babeljs from converting a function to a local var?

I have an app written in ES2015 and I'm using babeljs to transpile the code to ES5. 我有一个用ES2015编写的应用程序,正在使用babeljs将代码转换为ES5。 I have a single function which contains the code but this function is transpiled to a function expression assigned to a var . 我有一个包含代码的函数,但是此函数被转换为分配给var的函数表达式。 This would probably normally be fine but I have a number of wrappers in my JavaScript code which wraps up the output babel into various outputs (one for loading the object onto the window, another for wrapping it in an angular service etc) so that it can be consumed in many ways. 通常这可能没问题,但是我的JavaScript代码中有很多包装器,可以将输出babel打包为各种输出(一个用于将对象加载到窗口上,另一个用于将其包装在角度服务中等),以便可以被多种方式消耗。

I'm trying to consume it using Angular and here is an example of the source (ES2015) code: 我正在尝试使用Angular来使用它,这是源代码(ES2015)示例:

function code() {
  return {
    function1: function1,
    function2: function2
  }

  function function1() {
    const foo = "bar"
    //..
  }

  function function2() {
    //..
  }
}

this transpiles into: 转换为:

var code = function code() {
  return {
    function1: function1
    function2: function2
  };

  function function1() {
    var foo = "bar";
    //..
  }

  function function2() {
    //..
  }
}

Note that the whole thing is assigned to a var named code . 注意,整个事情都分配给一个名为codevar

In my wrapper, I wrap it in an angular service like this: 在我的包装器中,我将其包装在如下的角度服务中:

(function () {
    angular
        .module(angular._MODULE_)
        .service('someService', code);

    <%- include('../lib/code.js') %>
}());

where ../lib/code.js is the transpiled ES5 output. 其中../lib/code.js是转译的ES5输出。

This is no good for angular as it can't access the local var. 这对angular不利,因为它无法访问本地var。

How can I stop babel from assigning this to a var? 如何阻止babel将其分配给var?

You shouldn't count on hoisting to scopes that Babel does not know about. 您不应该依靠Babel不知道的范围来吊装。 Either wrap the ES6 first and transpile the whole script, or just use 要么先包装ES6并转换整个脚本,要么使用

(function () {
    <%- include('../lib/code.js') %>

    angular
        .module(angular._MODULE_)
        .service('someService', code);
}());

instead. 代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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