Skip to content

substrate-system/debug

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

debug

tests module types semantic versioning install size GZip size license

  • Cloudflare
  • Node
  • 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

npm i -D @substrate-system/debug

Browser usage: Use localStorage DEBUG key. Node.js usage: Use environment variable DEBUG.

Browser

In the browser, this looks for the DEBUG key in localStorage.

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'

Factor out of production

Two options: either dynamic imports or use your bundler to swap files.

Esbuild Bundler

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 received mode as an argument.

// 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.

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.

import { type Debug, noop } from '@substrate-system/debug/noop'

let debug:ReturnType<typeof Debug> = noop
if (import.meta.env.DEV) {
  const Debug = await import('/example-path/debug.js')
  debug = Debug('myApplication:abc')
}

HTML importmap

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

<script type="importmap">
{
  "imports": {
    "@substrate-system/debug": "/example-path/debug.js",
  }
}
</script>

Production

<script type="importmap">
{
  "imports": {
    "@substrate-system/debug": "data:text/javascript,export default function(){return()=>{}}"
  }
}
</script>

Tip

Using a data: URL means no network request at all for the noop.

Vite Example

In vite, you can use the transformIndexHtml plugin to swap out the import map depending on the environment at build time.

// 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:

<!DOCTYPE html>
<html lang="en">
<head>
  <script type="importmap">
      <%- IMPORT_MAP_CONTENT %>
  </script>
</head>

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
// 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.

cp ./node_modules/@substrate-system/debug/dist/index.js ./public/vendor/debug.js

# then build
NODE_ENV=staging vite build

Cloudflare

Either pass in an env record, or will look at globalThis for the DEBUG variable.

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.

import createDebug from '@substrate-system/debug/node'
const debug = createDebug('fooo')
debug('testing')

Call this with an env var of DEBUG=fooo

DEBUG=fooo node ./test/fixture/node.js

Config

Namespace

In browsers, this checks localStorage for DEBUG key. In Node.js, this checks the environment variable DEBUG.

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)

Enable all namespaces

localStorage.setItem('DEBUG', '*')

Enable specific namespaces

localStorage.setItem('DEBUG', 'myapp:auth,myapp:api,myapp:api:*')

Boolean

Pass in a boolean to enable or disable the debug instance. This will log with a random color.

import Debug from '@substrate-system/debug'
const debug = Debug(import.meta.env.DEV)  // for vite dev server

debug('hello')
// => DEV hello

Extend

You can extend the debugger to create new debug instances with new namespaces:

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:

const logSignVerbose = logSign.extend('verbose')
logSignVerbose('hello')  // auth:sign:verbose hello

Develop

browser

Start a vite server and log some things. This uses the example directory.

npm start

Run the Node example

npx esbuild --platform=node --bundle ./example/node.ts | DEBUG="hello:*" node

Try it with a different env var to see different logs:

npx esbuild --platform=node --bundle ./example/node.ts | DEBUG="hello:*,abc123:*" node

or

npm run example:node

Test

All tests

npm test

Node

npm run test:node

Cloudlfare

npm run test:cloudflare

Browsers

npm run test:browser

Contributors 3

  •  
  •  
  •