UNPKG

2.53 kBMarkdownView Raw
1# browser-env
2
3> Simulates a global browser environment using [`jsdom`](https://github.com/tmpvar/jsdom).
4
5[![Build Status](https://travis-ci.org/lukechilds/browser-env.svg?branch=master)](https://travis-ci.org/lukechilds/browser-env) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/browser-env/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/browser-env?branch=master) [![npm](https://img.shields.io/npm/dm/browser-env.svg)](https://www.npmjs.com/package/browser-env)
6
7This allows you to run browser modules in Node.js 4 or newer with minimal or no effort. Can also be used to test browser modules with any Node.js test framework. Please note, only the DOM is simulated, if you want to run a module that requires more advanced browser features (like `localStorage`), you'll need to polyfill that seperately.
8
9> ❗️**Important note**
10>
11> This module adds properties from the `jsdom` window namespace to the Node.js global namespace. This is explicitly [recommended against](https://github.com/tmpvar/jsdom/wiki/Don't-stuff-jsdom-globals-onto-the-Node-global) by `jsdom`. There may be scenarios where this is ok for your use case but please read through the linked wiki page and make sure you understand the caveats.
12
13## Install
14
15```shell
16npm install --save browser-env
17```
18
19Or if you're just using for testing you'll probably want:
20
21```shell
22npm install --save-dev browser-env
23```
24
25## Usage
26
27```js
28// Init
29require('browser-env')();
30
31// Now you have access to a browser like environment in Node.js:
32
33typeof window;
34// 'object'
35
36typeof document;
37// 'object'
38
39var div = document.createElement('div');
40// HTMLDivElement
41
42div instanceof HTMLElement
43// true
44```
45
46By default everything in the `jsdom` window namespace is tacked on to the Node.js global namespace (excluding existing Node.js properties e.g `console`, `setTimout`). If you want to trim this down you can pass an array of required properties:
47
48```js
49// Init
50require('browser-env')(['window']);
51
52typeof window;
53// 'object'
54
55typeof document;
56// 'undefined'
57```
58
59You can also pass a config object straight through to `jsdom`. This can be done with or without specifying required properties.
60
61```js
62require('browser-env')(['window'], { userAgent: 'My User Agent' });
63
64// or
65
66require('browser-env')({ userAgent: 'My User Agent' });
67```
68
69You can of course also assign to a function:
70
71```js
72var browserEnv = require('browser-env');
73browserEnv();
74
75// or
76
77import browserEnv from 'browser-env';
78browserEnv();
79```
80
81## License
82
83MIT © Luke Childs