How to remove global “use strict” added by babel

后端 未结 16 2173
不思量自难忘°
不思量自难忘° 2020-11-27 03:46

I\'m using function form of \"use strict\" and don\'t want global form which Babel adds after transpilation. The problem is I\'m using some libraries that aren\'t using \"us

相关标签:
16条回答
  • 2020-11-27 04:32

    Babel 5

    You'd blacklist "useStrict". For instance here's an example in a Gruntfile:

    babel: {
        options: {
            blacklist: ["useStrict"],
            // ...
        },
        // ...
    }
    

    Babel 6

    Since Babel 6 is fully opt-in for plugins now, instead of blacklisting useStrict, you just don't include the strict-mode plugin. If you're using a preset that includes it, I think you'll have to create your own that includes all the others, but not that one.

    0 讨论(0)
  • 2020-11-27 04:33

    Personally, I use the gulp-iife plugin and I wrap IIFEs around all my files. I noticed that the babel plugin (using preset es2015) adds a global "use strict" as well. I run my post babel code through the iife stream plugin again so it nullifies what babel did.

    gulp.task("build-js-source-dev", function () {
    	return gulp.src(jsSourceGlob)
          .pipe(iife())
    	  .pipe(plumber())
    	  .pipe(babel({ presets: ["es2015"] }))// compile ES6 to ES5
    	  .pipe(plumber.stop())
          .pipe(iife()) // because babel preset "es2015" adds a global "use strict"; which we dont want
          .pipe(concat(jsDistFile)) // concat to single file
    	  .pipe(gulp.dest("public_dist"))
    });

    0 讨论(0)
  • 2020-11-27 04:33

    Please use "es2015-without-strict" instead of "es2015". Don't forget you need to have package "babel-preset-es2015-without-strict" installed. I know it's not expected default behavior of Babel, please take into account the project is not mature yet.

    0 讨论(0)
  • 2020-11-27 04:35

    I just made a script that runs in the Node and removes "use strict"; in the selected file.

    file: script.js:

    let fs = require('fs');
    let file = 'custom/path/index.js';
    let data = fs.readFileSync(file, 'utf8');
    let regex = new RegExp('"use\\s+strict";');
    if (data.match(regex)){
        let data2 = data.replace(regex, '');
        fs.writeFileSync(file, data2);
        console.log('use strict mode removed ...');
    }
    else {
        console.log('use strict mode is missing .');
    }
    

    node ./script.js

    0 讨论(0)
提交回复
热议问题