Skip to content

Feature Request: Support for service worker environments #203

@dxh9845

Description

@dxh9845

Description / Use Case for a Feature
Hello!
Congrats on a fantastic library! I wanted to propose adding support for another type of Javascript runtime environment - service workers. Currently, usage of this library in a non-Node or Browser environment causes reference errors when referring to window. By adding another environment, this logger could be used in serverless environments such as Cloudflare Workers.

I have compiled a version of the library locally that checks for the presence of the importScripts global to determine an additional "serviceworker" environment. I also added the WebWorker lib types to the tsconfig to prevent the Typescript reference error.

 const environment = () => {
      switch (true) {
        case ![typeof window, typeof document].includes("undefined"):
          return "browser"
        case ![typeof importScripts].includes("undefined"):
          return "serviceworker"
        case Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]":
          return "nodejs"
        default:
          return "unknown"
      }
    }

    const env = environment()
    
    const isBrowser = env === "browser";
    const isNode = env === "nodejs"
...

My specific usecase is to use this library in a Cloudflare Worker, but I would implement a PR that attempts to be platform-agnostic.

Let me know your thoughts. Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions