use-import0.1.2 • Public • Published
Imports modules by name instead of by filepath
Tired of dealing with lengthy relative file paths in your
require statements? This module gives your project files access to the
use function, enabling you to import modules by name rather than by filepath. Module names are configured either via a JSON file placed in the project's root directory or an object passed in at application startup.
npm install use-import --save
To configure your project's names, create a new file in your project's root directory called use.json. Within this file, map out the modules' names to their respective filepaths:
// all key-value pairs in this file should follow the format of// "name": "filepath." Like so:"MyClass": "./src/data/MyClass""MyOtherClass": "./src/model/MyOtherClass"// all file paths should be expressed relative to the project's// root directory
For another way to handle configuration, see In-Code Configuration below.
Add the following code to the top of your project's main script or entry point:
// This call is REQUIRED at the start of the application// in order to make `use-import` work when using a use.json// file for configuration!var use = ;
use.load only needs to be called once in a project. From that point on, you can (and should) require the use function normally in any of your project files, like so:
var use = ;
use function acts as a wrapper around
require, allowing you to request modules by name or shorthand alias rather than having to bother with filepaths.
// so instead of having to write something like this...var MyClass = ;// ... you can simply refer to the module by namevar use = ;var MyClass = ;
Optional: In-Code Configuration
As an additional option, instead of creating and loading a use.json file at runtime, you can also pass in a name-filepath map in your project's entry point, instead of calling
// make this call in your entry point or start script INSTEAD of calling use.load as described above.var use =;
- removed USE_IMPORTER_LOAD_CALLED_TWICE error. Proved to be too much of a pain in situations involving multiple entry points (like unit tests).
- added use.unload function
- use.load() can now accept direct filepath to JSON file.
Bug reports, feature requests, pull requests and general feedback would all be appreciated.