How to Stop Babel from Transpiling 'This' to 'Undefined' (And Inserting "Use Strict")

How to stop babel from transpiling 'this' to 'undefined' (and inserting use strict)

For Babel >= 7.x

ES6 code has two processing modes:

  • "script" - When you load a file via a <script>, or any other standard ES5 way of loading a file
  • "module" - When a file is processed as an ES6 module

In Babel 7.x, files are parsed as "module" by default. The thing that is causing you trouble is that in an ES6 module, this is undefined, whereas in the "script" case, this varies depending on the environment, like window in a browser script or exports in CommonJS code. Similarly, "module" files are automatically strict, so Babel will insert "use strict";.

In Babel 7, you'll need to tell Babel what type your file is if you want to avoid this behavior. The simplest option would be to use the "sourceType" option to set sourceType: "unambiguous" in your Babel options, which essentially tells Babel to guess the type (scripts vs module), based on the presence of import and export statements. The primary downside there being that it's technically fine to have an ES6 module that doesn't use import or export, and those would be incorrectly treated as scripts. On the other hand, that's really not that common.

Alternatively, you can use Babel 7's "overrides" option to set specific files as scripts, e.g.

overrides: [{
test: "./vendor/something.umd.js",
sourceType: "script",
}],

Either approach allows Babel to know that some files are script types, and thus shouldn't have this converted to undefined.

For Babel < 7.x

ES6 code has two processing modes:

  • "script" - When you load a file via a <script>, or any other standard ES5 way of loading a file
  • "module" - When a file is processed as an ES6 module

When using Babel 6 and babel-preset-es2015 (or Babel 5), Babel by default assumes that files it processes are ES6 modules. The thing that is causing you trouble is that in an ES6 module, this is undefined and files are all strict, whereas in the "script" case, this varies depending on the environment, like window in a browser script or exports in CommonJS code.

If you are using Babel, the easiest option is to write your code without the UMD wrapper, and then bundle your file using something like Browserify to automatically add the UMD wrapper for you. Babel also provides a babel-plugin-transform-es2015-modules-umd. Both are geared toward simplicity, so if you want a customized UMD approach, they may not be for you.

Alternatively, you would need to explicitly list all of the Babel plugins in babel-preset-es2015, making sure to exclude the module-processing babel-plugin-transform-es2015-modules-commonjs plugin. Note, this will also stop the automatic addition of use strict since that is part of the ES6 spec too, you may want to add back babel-plugin-transform-strict-mode to keep your code strict automatically.

As of babel-core@6.13 presets are able to take options, so you can also do

{
"presets": [
[ "es2015", { "modules": false } ]
]
}

in your Babel config (.babelrc) to use babel-preset-es2015 with module processing disabled.

How to remove global use strict added by babel

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.

babel 7 - how to prevent adding of strict mode

Babel assumes by default that files being transformed are ES modules. Since that is not the case for you, you'll want to tell it that. You can check out the docs for the "sourceType" option, but essentially you want to add:

"sourceType": "script"

in your Babel options.

Disable/Ignore Babel strict mode for transpiling javascript files

I have figured out the solution.By default Babel parses the files as ES6 modules, which are strict by default.If we add the --source-type script in case one is using cli,then it will work.I am writing a simple command to transpile a single js file which will ignore strict mode,in case someone gets stuck on this in future.One key note is you need to upgrade to latest babel 7 to make it work.

babel test.js --presets=@babel/env --source-type script --out-file test_new.js

Bundle JS with rollup and Babel for use in IE11

I think as you enabled the option useBuiltIns: "usage" which means it will append code from corejs into your module files which is written with cjs style. So you have to add this plugin @rollup/plugin-commonjs to convert back to esm, then it will work:

import commonjs from '@rollup/plugin-commonjs';

export default {
// ...
plugins: [
// ...
commonjs(),
]
};

After installing babel I get an exception of undeclared variable

Ok.
It takes me a while to figure it out.

here's the solution:
Add that to the plugins in .babelrc

"plugins": [
["@babel/plugin-transform-modules-commonjs", {
"strictMode": false
}],
"angularjs-annotate"
]

Babel 6 regeneratorRuntime is not defined

babel-polyfill (deprecated as of Babel 7.4) is required. You must also install it in order to get async/await working.

npm i -D babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-loader

package.json

"devDependencies": {
"babel-core": "^6.0.20",
"babel-polyfill": "^6.0.16",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}

.babelrc

{
"presets": [ "es2015", "stage-0" ]
}

.js with async/await (sample code)

"use strict";

export default async function foo() {
var s = await bar();
console.log(s);
}

function bar() {
return "bar";
}

In the startup file

require("babel-core/register");
require("babel-polyfill");

If you are using webpack you need to put it as the first value of your entry array in your webpack configuration file (usually webpack.config.js), as per @Cemen comment:

module.exports = {
entry: ['babel-polyfill', './test.js'],

output: {
filename: 'bundle.js'
},

module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel', }
]
}
};

If you want to run tests with babel then use:

mocha --compilers js:babel-core/register --require babel-polyfill


Related Topics



Leave a reply



Submit