Search code examples
webpackecmascript-6babeljsbabel-loader

Babel 7 this becomes _this angularjs


I'm making an application using ES6, AngularJS and babel-loader 7.1.4, Webpack 3 . Everything worked fine until I created a service file:

This is my service:

'use strict';

module.exports = (ngModule) => {

    ngModule.service('$ui', () => {


        //#region Methods

        /*
        * Trigger windows resize function.
        * */
        this.reloadWindowSize = () => {
            $(window).resize();
        };

        //#endregion
    });
};

After transpilling source code from ES6 to ES2015, my service became:

module.exports = function (ngModule) {

    ngModule.service('$ui', function () {

        //#region Methods

        /*
        * Trigger windows resize function.
        * */
        _this.reloadWindowSize = function () {
            $(window).resize();
        };

        //#endregion
    });
};

As you see, this now becomes _this, therefore, I cannot execute the function in service file.

This is my babel configuration

{
    test: /\.js$/,
    exclude: /(node_modules|bower_components)/,
    use: {
        loader: 'babel-loader',
        options: {
            presets: [['env', { "modules": false }]]
        }
    }
}

What wrong am I doing ?

Can anyone help me please?

Thank you,


Solution

  • After reading this topic. I have found the answer.

    I changed my service implementation from :

    'use strict';
    
    module.exports = (ngModule) => {
    
        ngModule.service('$ui', () => {
    
    
            //#region Methods
    
            /*
            * Trigger windows resize function.
            * */
            this.reloadWindowSize = () => {
                $(window).resize();
            };
    
            //#endregion
        });
    };
    

    To this:

    module.exports = (ngModule) => {
    
        ngModule.service('$ui', () => {
    
            return {
    
                //#region Methods
    
                /*
                * Reload window size.
                * */
                reloadWindowSize: () => {
                    $(window).resize();
                }
    
                //#endregion
            }
        });
    };
    

    Within service declaration, I return a set of functions and it worked.

    Just want to let anyone know about this. It took me a night to find the answer.