Rodders Rodders - 2 months ago 13
AngularJS Question

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. I have a single function which contains the code but this function is transpiled to a function expression assigned to a

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.

I'm trying to consume it using Angular and here is an example of the source (ES2015) code:

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
.

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.

This is no good for angular as it can't access the local var.

How can I stop babel from assigning this to a var?

Answer

You shouldn't count on hoisting to scopes that Babel does not know about. Either wrap the ES6 first and transpile the whole script, or just use

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

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

instead.