babel / minify

:scissors: An ES6+ aware minifier based on the Babel toolchain (beta)
https://babeljs.io/repl
MIT License
4.39k stars 225 forks source link

when function write inside if condition statment, the declare function will only usable in that statment #929

Open tun100 opened 6 years ago

tun100 commented 6 years ago

Describe the bug when function write inside if condition statment, the declare function will only usable in that statment

To Reproduce I wrote example program, and upload to my github repo, please check this href https://github.com/LaiHuanMin/babelminify-issuecheck-for-function-scope

origin js

window.onload = () => {
    var obj = {
        testfunc: function(value){
            if(value === 'test1'){
                function scopefunc1(){
                    console.log('this is scope func 1');
                }
                var scopefunc2 = () => {
                    console.log();
                    console.log('this is scope func 2');
                }
                let scopefunc3 = () => {

                }
            }
            // that func should be exists
            scopefunc1();
            // if the if condition is true, also should be exists
            scopefunc2();
            // never exists whatever the condition result is
            scopefunc3();
        }
    }
    obj.testfunc("value");
}

Actual Output

window.onload = function() {
    ({
        testfunc: function c(a) {
            if ("test1" === a) var b = function() {
                    console.log(), console.log("this is scope func 2")
                };
            scopefunc1(), b(), scopefunc3()
        }
    }).testfunc("value")
};

Expected Output

window.onload = function() {
    ({
        testfunc: function c(a) {
            if ("test1" === a) {
                function scopefun1(){}   ; var scopefunc3 = () => {}; // i ignore the function content
            };
            scopefunc1(), b(), scopefunc3()
        }
    }).testfunc("value")
};

Stack Trace

If applicable,

Configuration

How are you using babel-minify?

babelrc:

module.exports = { "presets": [['@babel/preset-env', { modules: false, useBuiltIns: 'entry' }], "minify" ], "plugins": [ "@babel/plugin-transform-async-to-generator" ] }

Possible solution Function should be usable in the same scope, may be there's look like a bad code style, but it's very safty for compile old javascript file. I'm using babel minify to compile old project which using requirejs, i hope there's a config option can set the loose true, and safty compile the code into a runnable minify code.

Additional context node v 8.4.0
UBuntu 16.04 LTS