babel-plugin-access-undefined
This plugin prevents from getting an error while trying to access properties of undefined or null.
Example
Objects
const obj = { a: 2, b: 3 };
obj.a; // 2
obj.c; // undefined
obj.c.d; // undefined instead of an error
obj.c.d.e.f.g.h; // still undefined
Arrays
const obj = [1, 2, [3, 4]];
obj[1]; // 2
obj[3]; // undefined
obj[3][1]; // undefined instead of an error
obj[3][1][4][8]; // still undefined
Installation
npm install --save-dev babel-plugin-access-undefined
Usage
.babelrc
{
"plugins": ["access-undefined"]
}
After including this plugin in a .babelrc file, the transpiling doesn't happen immediatelly. You can control which objects should be transpiled by using the keywords:
-
safe::
switches the transpiling on -
unsafe::
switches the transpiling off
safe::
and unsafe::
can be applied to different kinds of expressions such as a member expression, a call expression or a function expression and many others.
You can mix the keywords together in order to achieve a desired result.
Example
This code:
const obj = { prop: 10 }
const a = obj.b
const c = safe::(() => {
const d = obj.e
const f = obj.g.h
obj.prop = 12
const i = unsafe::obj.j.k.l
obj.m.func()
})
const n = safe::obj.o.p
const r = safe::[obj[2], obj[4]]
const t = safe::({
u: w.x.y.z
})
will be transpiled into
const obj = { prop: 10 };
const a = obj.b;
const c = () => {
const d = obj && obj.e;
const f = obj && obj.g && obj.g.h;
obj.prop = 12;
const i = obj.j.k.l;
obj && obj.m && obj.m.func && obj.m.func();
};
const n = obj && obj.o && obj.o.p;
const r = [obj && obj[2], obj && obj[4]];
const t = {
u: w && w.x && w.x.y && w.x.y.z
};
Note
If you are using other plugins that use bind expression (e.g. babel-plugin-transform-function-bind) please bear in mind that you have to include this plugin before them in .babelrc file
{
"plugins": ["access-undefined", "transform-function-bind"]
}