Many developers only know a little about the basics of DevTool
The most used console.log()
is very useful for outputting values while the code is running, and can usually help pinpoint errors.
However, there is still an advanced usage that many people don’t know, so it has not been fully utilized. It is faster, easier and more useful. These advanced usages can be used for client-side scripting, web workers and service work. personnel.
Node.js
and Deno
runtime consoles also support many functions.
1. Use ES6 to deconstruct the output variable name
When monitoring multiple values, logging can become complicated. It is often necessary to add more information, such as
const x = 42;
console.log('variableX:', variableX);
// or
console.log(`variableX: ${ variableX }`);
/*
output:
variableX: 42
*/
A faster option is to use ES6 object destruction allocation. This will add the variable to the object with the matching attribute name.
In other words, just place { and }
to display its name and value:
console.log({ variableX });
/*
output:
{ variableX: 42 }
*/
2. Use the appropriate log message type
console.log()
is the easiest method well known:
console.log('no-frills log message');
But this is not the only type. Messages can be classified as information (the same processing as console.log()):
console.info('this is an information message');
warnings
:
console.warn('I warned you this could happen!');
errors
:
console.error('I\'m sorry Dave, I\'m afraid I can\'t do that');
Or less important debug
debug message:
console.debug('nothing to see here - please move along');
console.table()
can output object values in a more friendly format:
const obj = {
propA: 1,
propB: 2,
propC: 3
};
console.table( obj );
console.table()
can also be used for one-dimensional or multi-dimensional arrays:
const arr1 = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
];
console.table( arr1 );
Or an array of objects:
const arr2 = [
{ a: 1, b: 2, c: 3 },
{ a: 4, b: 5, c: 6 },
{ a: 7, b: 8, c: 9 }
];
console.table( arr2 );
Other options include:
console.dir( obj )
Display an interactive list of attributes in a JavaScript objectconsole.dirxml( element )
displays an interactive tree of descendant elements from the specified HTML or XML nodeconsole.clear()
clears all previous messages in the console.
3. Filter log messages
The browser displays log messages in appropriate colors, but they can also be filtered to show specific types.
Click the icon on the top left of the console
Please note that console.debug()
only displays the message when viewing the detailed
4. Use printf-type
message
All log types can use the C-style printf
message format , which defines a %
indicator, which is used to replace variables.
E.g:
console.log(
'The answer to %s is %d.',
'life, the universe and everything',
42
);
// The answer to life, the universe and everything is 42.
5. Recording style
You can style the log message using standard CSS passed as a string in the second parameter of any message type.
%c
message indicates where the style is applied, for example
console.log(
'%cOK, things are really bad now!',
`
font-size: 2em;
padding: 0.5em 2em;
margin: 1em 0;
color: yellow;
background-color: red;
border-radius: 50%;
`
);
The result in the DevTools console is:
6. Assertions using similar tests
console.assert()
When the condition fails, you can use a command like test to output a message.
You can use a condition to define an assertion, and then output one or more objects when the condition fails, for example
console.assert(
life === 42,
'life is expected to be',
42,
'but is set to',
life
);
Alternatively, you can use the message and replacement value:
console.assert(
life === 42,
'life is expected to be %s but is set to %s',
42,
life
);
When the condition fails, both of these options will display an assertion error:
7. Run stack trace
You can use the following command to output the log console.trace()
of all function calls that constitute the current execution point:
function callMeTwo() {
console.trace();
return true;
}
function callMeOne() {
return callMeTwo();
}
const r = callMeOne();
The trace shows the line of each call, which can be collapsed or expanded in the Console pane:
8. Group log messages
You can use console.group( label )
at the beginning and console.groupEnd()
end to divide log messages into named groups.
Message groups can be nested, collapsed or expanded ( console.groupCollapsed( label )
initially shows that the group is in a collapsed state):
// start log group
console.group('iloop');
for (let i = 3; i > 0; i--) {
console.log(i);
// start collapsed log group
console.groupCollapsed('jloop');
for (let j = 97; j < 100; j++) {
console.log(j);
}
// end log group (jloop)
console.groupEnd();
}
// end log group (iloop)
console.groupEnd();
9. Use the performance timer
The time( label )
command starts a timer. timeEnd( label )
will report the elapsed time (in milliseconds) after reaching the associated command.
Timers can be used to evaluate the performance of operations-easier and more accurate than managing your own Date() calculations, for example
// start timer
console.time('bigloop');
for (let i = 999999999; i > 0; i--);
// show elapsed time
console.timeEnd('bigloop');
You can add up to 10,000
timers on a page, and the console.timeLog( label )
command will report the elapsed time without stopping the timer.
A similar option is console.count( label )
report the number of times the command was called.
console.countReset( label )
the named counter to zero.
10. Debug and monitor functions by name
DevTools Sources
panel (or Debugger in Firefox) allows you to open the file and set breakpoints by clicking the line number.
Chrome-based browsers also allow you debug( functionName )
in the console, for example
debug( doSomething );
The function must be available in the global namespace, and the browser will launch it immediately after calling the debugger. You can undebug( functionName )
or by reloading the page.
The monitor( functionName )
and its associated unmonitor( functionName )
commands are used in a similar way. They did not stop the execution, but instead recorded each call to the function and displayed the passed parameters:
function doSomething called with arguments: "hello", 2
11. Find and fix event listeners
The Firefox DevTools inspector panel displays an event icon next to any DOM element to which a handler is attached.
Click the icon to view the function name, and then click the arrow icon on the left to expand the code.
In addition, the "Open in Debugger" icon can find the handler in the "Debugger" pane, so you can set breakpoints:
Chrome's implementation is not ideal, but you can view all event listeners DOM
node to the getEventListeners()
For example, getEventListeners( $0 )
shows the listener DOM
node currently highlighted in the Elements panel:
12. Copy attributes to clipboard
console copy()
command can copy any value to the clipboard. It can be a primitive value, an array, an object or a DOM node.
After passing the DOM node, copy()
the HTML of the element and all its child elements on the clipboard.
It is equivalent to right-clicking a node, then selecting "Copy", and then selecting "Copy External HTML".
This command copy( document.documentElement )
copy the entire HTML
document. You can paste it into a text editor to make it easier to read the markup.
At last
The browser DevTools has evolved from a basic console to a complex development and debugging environment.
console.log()
will always be popular, but other options may provide a faster and easier way to achieve zero errors!
This article is translated from the article: 12 Ways to Improve Your DevTools Console Logging
- Vue3 Family Bucket + Element Plus + Vite + TypeScript + Eslint Project Configuration Best Practice
- 10 advanced techniques to improve happiness in TypeScript
- Recommend 7 heavy open source projects for Vue2 and Vue3 source code decryption analysis
Welcome to pay attention to the public : "160901700c0178 full stack practice ", reply to " e-book ", you can get the following 300 technical essence books, cat brother wx: CB834301747.
By reading this article, if you have any gains, you can and and look at . This will become my motivation for continuing to share, thank you~
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。