A small library providing utility methods to manage modules, particularly loading and uncaching (removing from cache). Handy for unit testing where having freshly loaded modules is wanted.
npm install module-fu --save-dev
This example assumes you'll be using it in development only.
var mf = require('module-fu');
mf.setResolver(function(moduleName) { return require.resolve(moduleName); });
var expect = require('chai').expect;
describe('my-cool-module', function() {
it('rocks because I reload the module.', function() {
var info = mf.find('./my-cool-module.js');
expect(info.length).to.equal(0);
var mcm = mf.load('./my-cool-module.js');
info = mf.find('./my-cool-module.js');
expect(info.length).to.equal(1);
expect(d1.hello()).to.equal('hello world');
mf.remove('./my-cool-module.js');
info = mf.find('./my-cool-module.js');
expect(info.length).to.equal(0);
});
});
npm test
Sets the function used to resolve module references. Usually needs setting from where this module is loaded.
- resolverFn - A function that performs the equivalent of require.resolve()
var mf = require('module-fu');
mf.setResolver(function(moduleName) { return require.resolve(moduleName); });
var mcm = mf.load('./my-cool-module.js');
Removes a module from the cache
- moduleName - the name of the module to remove from the cache.
Searches the cache for references to a module.
- moduleName - the name of the module to search for.
- callback - optional callback. If specified it will be called for each occurrence found.
If no callback is specified => an array of results found. If a callback is specified => undefined.
Loads a module and optionally retrieves an import. Designed to give nice messages when the module or import is not found so mistakes in writing tests are picked up quickly.
- moduleName - the name of the module to load.
- importName - Optional name of the import to get and return for the module.
If an importName is specified => The module exported property with the same name. If no importName is specified => The module is returned.
Reloads a module and optionally retrieves an import. Similar to load but first removes the module from the cache.
- moduleName - the name of the module to reload.
- importName - Optional name of the import to get and return for the module.
If an importName is specified => The module exported property with the same name. If no importName is specified => The module is returned.
Adapted from this answer to a StackOverflow question.