Quick Tip – debug()

综合技术 2018-09-11 阅读原文

If you’re using any sort of linting in your code (and you should), you will more than likely come across a default rule that screams at you for leaving all those handy console.log
s in your code. Those logs sure give useful information, but it is admittedly an unprofessional (and potentially insecure) thing to leave in your production code. Are there any other options?

Turns out, yes! I’m not talking about manually modifying your build process to strip console statements or anything like that, but Ember actually has a built in tool for this:

import { debug } from "@ember/debug";
import Component from "@ember/component";
import layout from "../templates/components/mycomponent";

export default Component.extend({
	layout,
	actions: {
		pressButton() {
			debug("Pressed button");
			this.doSomething();
		}
	}
});

The key line is right up on the top, importing debug
from the @ember/debug
module. This effectively works like a console.log
, where it will print a string
to the console BUT has the added benefit of being stripped from the production builds of your Ember project. This can really be useful when you are building complex components, and let you see, for example, a chain of functions being called throughout different subcomponents. You would be able to easily see a break in the chain with your log, and not have to worry about cleanup later.

The one caveat here, is that debug
will only
print a string. If you want to use the fancier inspection tools of the browser to look at the array’s items or an object’s properties, then you will have to look elsewhere for that!

Bonus tip: You can also import assert
from the same @ember/debug
and use it in a similar way
as a test. For example, if you have a required property in a component, assert its existence in the init
hook so that anyone who uses it wrong will see the issue right away in console, instead of wondering why part of the component is blank!

责编内容by:Wombat Security Development 【阅读原文】。感谢您的支持!