- Updated readme.md with complete API reference and usage examples - Added readme.hints.md with architecture and implementation details - Improved documentation structure and clarity - Version bump to 5.0.13
7.2 KiB
@push.rocks/smartenv
A cross-platform TypeScript library for detecting and managing runtime environments. It provides comprehensive environment detection capabilities and safe module loading for both Node.js and browser contexts.
Install
To install @push.rocks/smartenv
, you need Node.js and pnpm installed. Then, run the following command:
pnpm install @push.rocks/smartenv --save
Usage
@push.rocks/smartenv
is a powerful utility for managing and accessing environment-specific information within your application. It enables your code to adapt seamlessly to different environments such as development, testing, and production.
Getting Started
First, import the Smartenv
class from the package:
import { Smartenv } from '@push.rocks/smartenv';
Initializing Smartenv
Create an instance of Smartenv
to access all environment detection and module loading features:
const smartEnv = new Smartenv();
Core Features
- Runtime Environment Detection: Instantly detect whether your code is running in Node.js or browser
- Operating System Detection: Identify Mac, Windows, or Linux platforms in Node.js environments
- CI Environment Detection: Detect if running in a continuous integration environment
- Safe Module Loading: Load modules conditionally based on the runtime environment
- Browser Information: Access user agent information in browser contexts
- Node.js Version: Get the current Node.js version when running in Node.js
API Reference
Environment Detection
isNode: boolean
Returns true
if running in a Node.js environment.
if (smartEnv.isNode) {
console.log('Running in Node.js');
}
isBrowser: boolean
Returns true
if running in a browser environment.
if (smartEnv.isBrowser) {
console.log('Running in browser');
}
runtimeEnv: string
Returns the runtime environment as a string ('node' or 'browser').
console.log(`Runtime: ${smartEnv.runtimeEnv}`);
isCI: boolean
Returns true
if running in a CI environment (checks for CI environment variable).
if (smartEnv.isCI) {
console.log('Running in CI environment');
}
Platform Detection (Node.js only)
isMacAsync(): Promise<boolean>
Asynchronously checks if running on macOS.
const isMac = await smartEnv.isMacAsync();
if (isMac) {
console.log('Running on macOS');
}
isWindowsAsync(): Promise<boolean>
Asynchronously checks if running on Windows.
const isWindows = await smartEnv.isWindowsAsync();
if (isWindows) {
console.log('Running on Windows');
}
isLinuxAsync(): Promise<boolean>
Asynchronously checks if running on Linux.
const isLinux = await smartEnv.isLinuxAsync();
if (isLinux) {
console.log('Running on Linux');
}
Runtime Information
nodeVersion: string
Returns the Node.js version (only available in Node.js environment).
if (smartEnv.isNode) {
console.log(`Node.js version: ${smartEnv.nodeVersion}`);
}
userAgent: string
Returns the browser user agent string (only available in browser environment).
if (smartEnv.isBrowser) {
console.log(`Browser: ${smartEnv.userAgent}`);
}
Module Loading
getEnvAwareModule(options)
Loads a module appropriate for the current environment. In Node.js, it uses dynamic import; in browsers, it loads a script via URL.
const module = await smartEnv.getEnvAwareModule({
nodeModuleName: 'node-fetch',
webUrlArg: 'https://unpkg.com/whatwg-fetch@3.6.2/dist/fetch.umd.js',
getFunction: () => window.fetch
});
getSafeNodeModule<T>(moduleName, runAfterFunc?)
Safely loads a Node.js module with error handling. Only works in Node.js environment.
const fs = await smartEnv.getSafeNodeModule('fs');
if (fs) {
// Use fs module
}
// With post-load function
const express = await smartEnv.getSafeNodeModule('express', async (mod) => {
console.log('Express loaded successfully');
});
getSafeWebModule(url, getFunction)
Safely loads a web module via script tag. Only works in browser environment. Prevents duplicate loading of the same script.
const jQuery = await smartEnv.getSafeWebModule(
'https://code.jquery.com/jquery-3.6.0.min.js',
() => window.jQuery
);
Debugging
printEnv()
Prints the current environment information to the console for debugging purposes.
await smartEnv.printEnv();
// Output in Node.js: "running on NODE" + version
// Output in browser: "running on BROWSER" + user agent
Common Use Cases
1. Isomorphic Module Loading
// Define environment-specific implementations
const cryptoModule = await smartEnv.getEnvAwareModule({
nodeModuleName: 'crypto',
webUrlArg: 'https://unpkg.com/crypto-js@4.1.1/crypto-js.js',
getFunction: () => window.CryptoJS
});
2. Platform-Specific Operations
if (smartEnv.isNode) {
const os = await smartEnv.getSafeNodeModule('os');
console.log(`Home directory: ${os.homedir()}`);
} else {
console.log('Browser environment - no filesystem access');
}
3. CI/CD Pipeline Detection
if (smartEnv.isCI) {
// Run extended tests or different build configuration
console.log('Running in CI - enabling extended test suite');
} else {
console.log('Local development environment');
}
4. Dynamic Script Loading in Browser
if (smartEnv.isBrowser) {
// Load analytics only in browser
await smartEnv.getSafeWebModule(
'https://www.google-analytics.com/analytics.js',
() => window.ga
);
}
TypeScript Support
The package is written in TypeScript and provides full type definitions. The main type export is:
export interface IEnvObject {
name: string;
value: string;
}
License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the license file within this repository.
Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.