Debug utility
npm install @substrate-system/debug* [x] Cloudflare
* [x] Node
* [x] browsers
A tiny JavaScript debugging utility that works in Node and browsers.
Use environment variables to control logging in Node, and localStorage
in browsers. Keep your ridiculous console log statements out of production.
This is based on debug.
It's been rewritten to use contemporary JS.
In the browser, this uses localStorage key 'DEBUG'.
In Node, it uses the environment variable DEBUG.
Plus, see the docs
generated by typescript.
Contents
- Install
- Browser
* Factor out of production
+ Esbuild Bundler
+ Vite Bundler
+ Dynamic Imports
+ Dynamic Imports
* HTML importmap
+ Development
+ Production
* Vite Example
+ Staging Environment
- Cloudflare
- Node JS
- Config
* Namespace
* Enable all namespaces
* Enable specific namespaces
* Boolean
* Extend
- Develop
* browser
* Run the Node example
- Test
* All tests
* Node
* Cloudlfare
* Browsers
``sh`
npm i -D @substrate-system/debug
Browser usage: Use localStorage DEBUG key.DEBUG
Node.js usage: Use environment variable .
In the browser, this looks for the DEBUG key in localStorage.
`js
import Debug from '@substrate-system/debug'
// Set DEBUG in localStorage
localStorage.setItem('DEBUG', 'myapp:*')
// create debug instance
const debug = Debug('myapp:component')
debug('hello logs')
// will log, because DEBUG in localStorage matches 'myapp:component'
`
Two options: either dynamic imports or use your bundler to swap files.
#### Esbuild Bundler
`sh`
esbuild src/app.js --bundle --alias:@substrate-system/debug=@substrate-system/debug/noop > ./dist/app.js
#### Vite Bundler
Use the resolve.alias configuration. Pass a function that receives mode as
an argument.
`js
// vite.config.js
import { defineConfig } from 'vite';
import path from 'node:path';
export default defineConfig(({ mode }) => {
const isProd = mode === 'production';
return {
resolve: {
alias: {
// When in production, swap 'my-debug-module' for a local no-op file
'@substrate-system/debug': (isProd ?
'@substrate-system/debug/noop' :
'@substrate-system/debug'),
},
},
};
});
`
#### Dynamic Imports
Use dynamic imports
to keep this entirely out of production code, so your bundle is smaller.
Either build this module to the right path, or copy the
bundled JS included here, then you can dynamically import the module.
`sh`
cp ./node_modules/@substrate-system/debug/dist/browser/index.min.js ./public/debug.js
#### Dynamic Imports
> [!NOTE]
> We export noop here; it has the same type signature as debug.
`ts
import { type Debug, noop } from '@substrate-system/debug/noop'
let debug:ReturnType
if (import.meta.env.DEV) {
const Debug = await import('/example-path/debug.js')
debug = Debug('myApplication:abc')
}
`
Or use the HTML importmap script tag
to replace this in production. In these examples, you would need to build this
module or copy the minified JS file to the right directory, so it is accessible
to your web server.
#### Development
`html`
#### Production
`html`
> [!TIP]
> Using a data: URL means no network request at all for the noop.
In vite, you can use the transformIndexHtml plugin to swap out the import
map depending on the environment at build time.
`js
// vite.config.js
import { defineConfig } from 'vite'
// https://vitejs.dev/config/
export default defineConfig({
// ...
root: 'example',
plugins: [
{
name: 'html-transform',
transformIndexHtml (html) {
const isProduction = process.env.NODE_ENV === 'production'
const map = isProduction ?
'{ "imports": { "@substrate-system/debug": "data:text/javascript,export default function(){return()=>{}}" } }' :
'{ "imports": { "@substrate-system/debug": "../node_modules/@substrate-system/debug/dist/index.js" } }'
return html.replace('<%- IMPORT_MAP_CONTENT %>', map)
},
},
],
// ...
})
`
And the HTML:
`html`
#### Staging Environment
For staging, you do still want the debug logs, but we need to copy the debug
file into our public directory so it is accessible to the web server.
##### Vite Config
`js
// vite.config.js
{
// ...
plugins: [
{
name: 'html-transform',
transformIndexHtml (html) {
const isProduction = process.env.NODE_ENV === 'production'
const isStaging = process.env.NODE_ENV === 'staging'
let map
if (isProduction && !isStaging) {
map = '{ "imports": { "@substrate-system/debug": "data:text/javascript,export default function(){return()=>{}}" } }'
} else if (isStaging) {
map = '{ "imports": { "@substrate-system/debug": "/vendor/debug.js" } }'
} else { // is dev
map = '{ "imports": { "@substrate-system/debug": "../node_modules/@substrate-system/debug/dist/index.js" } }'
}
return html.replace('<%- IMPORT_MAP_CONTENT %>', map)
},
},
],
// ...
build: {
rollupOptions: {
external: ['@substrate-system/debug'],
},
}
// ...
}
`
##### Build script
Copy the file to the public directory.
`sh
cp ./node_modules/@substrate-system/debug/dist/index.js ./public/vendor/debug.js
-------------------
Cloudflare
Either pass in an env record, or will look at
globalThis for
the DEBUG variable.`js
import Debug from '@substrate-system/debug/cloudflare'const myEnvVar = {
DEBUG: 'abc:*'
}
const debug = Debug('abc:123', myEnvVar)
`Node JS
Run your script with an env variable,
DEBUG.`js
import createDebug from '@substrate-system/debug/node'
const debug = createDebug('fooo')
debug('testing')
`Call this with an env var of
DEBUG=fooo
`sh
DEBUG=fooo node ./test/fixture/node.js
`Config
$3
In browsers, this checks localStorage for DEBUG key. In Node.js, this checks
the environment variable DEBUG.`js
import Debug from '@substrate-system/debug'// In browser: checks localStorage.getItem('DEBUG')
const debug = Debug('example')
// Log if no namespace is set in localStorage
const debug = Debug(import.meta.env.DEV)
`$3
`js
localStorage.setItem('DEBUG', '*')
`$3
`js
localStorage.setItem('DEBUG', 'myapp:auth,myapp:api,myapp:api:*')
`$3
Pass in a boolean to enable or disable the
debug instance. This will log
with a random color.`js
import Debug from '@substrate-system/debug'
const debug = Debug(import.meta.env.DEV) // for vite dev serverdebug('hello')
// => DEV hello
`$3
You can extend the debugger to create new debug instances with new namespaces:
`js
const log = Debug('auth')// Creates new debug instance with extended namespace
const logSign = log.extend('sign')
const logLogin = log.extend('login')
window.localStorage.setItem('DEBUG', 'auth,auth:*')
log('hello') // auth hello
logSign('hello') // auth:sign hello
logLogin('hello') // auth:login hello
`Chained extending is also supported:
`js
const logSignVerbose = logSign.extend('verbose')
logSignVerbose('hello') // auth:sign:verbose hello
`------------------------------------------------------------------
Develop
$3
Start a
vite server and log some things. This uses
the example directory.`sh
npm start
`$3
`sh
npx esbuild --platform=node --bundle ./example/node.ts | DEBUG="hello:*" node
`Try it with a different env var to see different logs:
`sh
npx esbuild --platform=node --bundle ./example/node.ts | DEBUG="hello:,abc123:" node
`
or
`sh
npm run example:node
`
Test
$3
`sh
npm test
`$3
`sh
npm run test:node
`$3
`sh
npm run test:cloudflare
`$3
`sh
npm run test:browser
``