mirror of https://github.com/sveltejs/svelte
feat: provide guidance in browser console when logging `$state` objects (#13142)
* feat: provide guidance in browser console when logging `$state` objects Wrap console.log/warn/error statements in DEV mode with a check whether or not they contain state objects. Closes #13123 This is an alternative or enhancement to #13070. Alternative if we deem it the better solution. Enhancement because it's not as robust as a custom formatter: We only check the top level of each entry (though we could maybe traverse a few levels), and if you're logging class instances, snapshot currently stops at the boundaries there and so you don't get snapshotted values for these (arguably this is a more general problem of $inspect and $state.snapshot), whereas with custom formatter it doesn't matter at which level you come across it. * lint * use normal warning mechanism, so we can link to docs etc * add a few more methods --------- Co-authored-by: Rich Harris <rich.harris@vercel.com>better-docs-for-css-injected
parent
836bc605f4
commit
ed7611b163
@ -0,0 +1,5 @@
|
||||
---
|
||||
'svelte': patch
|
||||
---
|
||||
|
||||
feat: provide guidance in browser console when logging $state objects
|
@ -0,0 +1,30 @@
|
||||
import { STATE_SYMBOL } from '../constants.js';
|
||||
import { snapshot } from '../../shared/clone.js';
|
||||
import * as w from '../warnings.js';
|
||||
|
||||
/**
|
||||
* @param {string} method
|
||||
* @param {...any} objects
|
||||
*/
|
||||
export function log_if_contains_state(method, ...objects) {
|
||||
let has_state = false;
|
||||
const transformed = [];
|
||||
|
||||
for (const obj of objects) {
|
||||
if (obj && typeof obj === 'object' && STATE_SYMBOL in obj) {
|
||||
transformed.push(snapshot(obj, true));
|
||||
has_state = true;
|
||||
} else {
|
||||
transformed.push(obj);
|
||||
}
|
||||
}
|
||||
|
||||
if (has_state) {
|
||||
w.console_log_state(method);
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
console.log('%c[snapshot]', 'color: grey', ...transformed);
|
||||
}
|
||||
|
||||
return objects;
|
||||
}
|
Loading…
Reference in new issue