https://github.com/ralphv/require-inject-scope
Inject scoped variables when requiring a file in Node.js
https://github.com/ralphv/require-inject-scope
inject nodejs require scope variables
Last synced: 12 months ago
JSON representation
Inject scoped variables when requiring a file in Node.js
- Host: GitHub
- URL: https://github.com/ralphv/require-inject-scope
- Owner: ralphv
- License: other
- Created: 2017-04-23T07:58:56.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2017-04-23T11:16:31.000Z (almost 9 years ago)
- Last Synced: 2025-02-24T02:53:27.085Z (12 months ago)
- Topics: inject, nodejs, require, scope, variables
- Language: JavaScript
- Size: 10.7 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: ChangeLog
- License: LICENSE
Awesome Lists containing this project
README
## require-inject-scope - Inject scoped variables when requiring a file.
[](https://nodei.co/npm/require-inject-scope/)
[](https://travis-ci.org/ralphv/require-inject-scope)
[](https://coveralls.io/github/ralphv/require-inject-scope?branch=master)
* [What is it?](#what-is-it)
* [Getting started](#getting-started)
* [Usage](#usage)
* [License](#License)
* [Changelog](#Changelog)
## What is it
The built in `require` of Node.js does not have a way to allow you to inject scoped variables.
The variables `module`, `exports`, `__dirname`, `__filename`... are available in the context of a required file but there is no easy way to provide your own variables.
Many developers will revert to using either globally defined variables or using singleton variables like `globals`, but neither of these are best practices.
This library allows you to inject your own variables to the context of the required file.
## Getting started
$ npm install --save require-inject-scope
## Usage
require this library as early as possible in your own code.
```javascript
require("require-inject-scope");
```
require will work normally as expected.
When you need to inject variables into a scope, instead of calling `require` with one parameter which
is the `path`, you call it using an array with exactly two elements.
The first element is the standard `path` and the second element will be an object having properties as variable names to inject and their values.
This is most useful when creating a plugin architecture where you want to provide the plugins a list of defined variables without requiring your plugins to require them manually.
example:
```javascript
require(["./sample.js", {"$config":configObject, "$helper": helperObject}]);
```
The file sample.js will have the two variables `$config` and `$helper` defined in its scope similar to the standard available variables.
### License
require-inject-scope is licensed under the [MIT](https://github.com/ralphv/require-inject-scope/raw/master/LICENSE).
### Changelog
* 1.0.0: Initial version