https://github.com/polioan/global-js
get, set global values in any js env
https://github.com/polioan/global-js
global globalthis pollute pollution testing window
Last synced: over 1 year ago
JSON representation
get, set global values in any js env
- Host: GitHub
- URL: https://github.com/polioan/global-js
- Owner: polioan
- License: mit
- Created: 2023-07-24T00:09:20.000Z (almost 3 years ago)
- Default Branch: master
- Last Pushed: 2023-08-05T05:45:24.000Z (almost 3 years ago)
- Last Synced: 2025-01-07T09:29:10.280Z (over 1 year ago)
- Topics: global, globalthis, pollute, pollution, testing, window
- Language: JavaScript
- Homepage: https://www.npmjs.com/package/@polioan/global-js
- Size: 60.5 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
# global-js
[](https://www.npmjs.com/package/@polioan/global-js)
[](https://opensource.org/licenses/MIT)
get, set global values in any js env
## Use case
### Test
```ts
import { setGlobal, getEnv } from '@polioan/global-js'
function toTest() {
return 333
}
if (getEnv('NODE_ENV') === 'test') {
setGlobal('toTest', toTest)
}
```
### Global cache (useful for hot reload)
```ts
import { getEnv, getGlobal, setGlobal } from '@polioan/global-js'
import { PrismaClient } from '@prisma/client'
export const prisma: PrismaClient = getGlobal('prisma') ?? new PrismaClient({})
if (getEnv('NODE_ENV') !== 'production') {
setGlobal('prisma', prisma)
}
```
### Libs for browser
```ts
import { setGlobal } from '@polioan/global-js'
class Myjquery {}
setGlobal('$', new Myjquery())
```
### Polyfills
```ts
import { setGlobal } from '@polioan/global-js'
if (typeof structuredClone === 'undefined') {
setGlobal('structuredClone', value => JSON.parse(JSON.stringify(value)))
}
```
### Creating global libraries
```ts
import { setGlobal } from '@polioan/global-js'
declare global {
var calculate: (a: number, b: number) => number
}
setGlobal('calculate', (a: number, b: number) => a + b)
const test = calculate(2, 3) // will work
```
## Install
### npm
```shell
npm i @polioan/global-js
```
### yarn
```shell
yarn add @polioan/global-js
```
### CDN
```html
setGlobal('some', 'test')
```
### Deno
```ts
import { setGlobal } from 'https://deno.land/x/global_js@2.0.1/src/index.ts'
setGlobal('some', 'test')
```