require-wrapper
v1.0.0
Published
A wrapper module for Node's require to use for requiring dynamic dependencies in Webpack environment
Downloads
4
Readme
require-wrapper
A wrapper module for Node's require to use for requiring dynamic dependencies in Webpack environment.
Installation
npm install require-wrapper --save
Usage
In Webpack configuration file exclude this module from parsing by setting module.noParse option:
module.exports = {
// ...
module: {
rules: {
// ...
},
noParse: /require-wrapper/
}
};
or
module.exports = {
// ...
module: {
rules: {
// ...
},
noParse: function(content) {
return /require-wrapper/.test(content);
}
}
};
In your source code require the dependency module dynamically:
dynamic/hello.js
module.exports = function sayHello() {
console.log('hello world!');
};
index.js
var nodeRequire = require('require-wrapper');
var helloModulePath = path.resolve(__dirname, 'dynamic/hello.js');
var sayHello = nodeRequire(helloModulePath);
sayHello(); // => hello world!
Why?
Sometimes in Node applications you still need to require dynamic modules but Webpack parses
require calls differently. If it's not
the case you need then wrap Node's require
function as proposed in this module.