How to ignore compile `require` to `__webpack_require__` in webpack? - node.js

I figure out this question because I use webpack to bundle the code with vm module in it.
For example:
const vm = require('vm');
vm.runInNewContext(`
const querystring = require('querystring');
console.log(querystring.parse('foo=bar&abc=xyz&abc=123'));
`, {
console,
require,
});
this code run in node is well. when I bundle it by webpack#1.14. It seems like:
nodeVm.runInNewContext("\n
const querystring = require('querystring');\n\n
console.log(querystring.parse('foo=bar&abc=xyz&abc=123'));\n ",{
console: console,
require: __webpack_require__(296)
});
by webpack#2.3.2. It seems like
nodeVm.runInNewContext("\n
const querystring = require('querystring');\n\n
console.log(querystring.parse('foo=bar&abc=xyz&abc=123'));\n ", {
console: console,
require: !(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())
});
because the require changed to __webpack_require__, the querystring module in vm will be notFound.
Is there any ways to make webpack ignore to change the require to __webpack_require__?

I am sure that it works if you want to keep a require as it is, not sure if it works also in your case.
There exist the variable __non_webpack_require__ exactly for that, follow the documentation
const a = __non_webpack_require__(myvar);
becomes:
const a = require(myvar);
after being compiled by webpack.

Related

Node unable to find local module

I was testing a very simple module to see if it works and keep on getting an error stating that node cannot find my module.
//mymodule.js
greeting = 'hello'
module.exports = greeting;
// main.js
const s = require('exportsPractice\mymodule.js');
console.log(s);
The error I get is shown here
Try using:
const s = require('./exportsPractice/mymodule.js');
And make sure the path is correct.

I get require is not defined error if I call it from external files

Hi,
I made an app for node.js so my app.js looks like this:
global.fs = require("fs");
global.vm = require('vm');
var includefile = function(path) {
var code = fs.readFileSync(path);
vm.runInThisContext(code, path);
}.bind(this);
includefile("variables.js");
as for variables.js I have this:
global.app = require("express")();
but when I start the app I get this error:
require is not defined at variables.js
why is it that requires loads fine if executed from app.js but not from an external file?
Thank you.
I'm a little confused, is variables.js just another source file in your project? All you should need to do is require the file in like you've done at the top. As an example for variables.js:
const Variables = {
fs: "some_value"
};
module.exports = Variables;
And for app.js
const { Variables } = require("./variables.js");
const fs = Variables.fs;
Executing console.log(fs); in app.js will print "some_value". Same can be done with functions.
If variables.js is part of your project code, you should use the answer of M. Gercz.
If it's not part of your project code and you want to get some information from it, you could use a json file:
app.js
const variables = require('variables.json');
console.log(variables.whatever);
variables.json
{ whatever: "valuable information" }
If it's not certain, that variables.json is preset, you can do a check using fs.existsSync;
Notice: As jfriend00 commented, using global is not recommended.

What does require('..') mean?

I am new to node.js and have been trying to test some code using yarn. At the moment I am using the following code:
const assert = require('assert')
const username = process.env.HDFS_USERNAME || 'webuser'
const endpoint1 = process.env.HDFS_NAMENODE_1 || 'namenode1.lan'
const endpoint2 = process.env.HDFS_NAMENODE_2 || 'namenode2.lan'
const homeDir = `/user/${username}`
const basePath = process.env.HDFS_BASE_PATH || homeDir
const nodeOneBase = `http://${endpoint1}:9870`
const nodeTwoBase = `http://${endpoint2}:9870`
const webhdfs = require('..')
const should = require('should')
const nock = require('nock')
describe('WebHDFSClient', function () {
const oneNodeClient = new (require('..')).WebHDFSClient({
namenode_host: endpoint1
});
})
that I've got from this repo:
https://github.com/ryancole/node-webhdfs/blob/master/test/webhdfs.js
and when I try to run yarn test I get the following error:
Cannot find module '..'
Require stack:
- myrepo/test/lib/hdfs.js
- myrepo/test/tests.js
- myrepo/node_modules/mocha/lib/mocha.js
- myrepo/node_modules/mocha/index.js
- myrepo/node_modules/mocha/bin/_mocha
Error: Cannot find module '..'
As you can see, require('..') is used couple of times in the code and I can not figure out what it means. I've found posts on require('../') which I think is not exactly the same as this one.
The inbuilt node.js require function uses a quite complex package resolution algorithm. So there are lots of things that may influence it.
A. Defaulting to index.js
node.js implicitly requires a file named index.js if no file name is specified.
So require("..") translates to require("../index.js")
B. The main package property.
If you require is inside a module and points to the root of the module it will read the main property from the packages package.json and require the file specified there.
So given this package definition (package.json)
{
"main": "./fileA.js"
}
The call to require("..") will be translated to require("../fileA.js")
Resources
Good explanatory blog entry
Official Docs

exports is not defined when running node.js script using vm in strict mode

I see this code in many modules:
var app = exports = module.exports = {};
But I have some problem executing these modules using Node.js VM in strict mode.
Here a demonstration:
var code = `
'use strict'; // Works if I remove this line
var app = exports = module.exports;
`;
var vm = require('vm');
var vmModule = { exports: {} };
var context = vm.createContext({
exports: vmModule.exports,
module: vmModule
});
var script = new vm.Script(code);
script.runInContext(context);
console.log("ok");
If I run this code I receive a exports is not defined error.
Without use strict the above code works fine.
Why a similar declaration works on a standard Node module but not inside a vm script? Should I declare the context in a different way?
As pointed by #mscdex this is probably an issue with node. See github.com/nodejs/node/issues/5344.
A possible workaround that seems to work (I hope without other implications) is to wrap all code inside an iife function:
const iifeCode = `(function(exports){${code}}(module.exports));`;
Then execute iifeCode instead of code:
var script = new vm.Script(iifeCode);

in nodejs, how to use 'require' in a function created with 'new Function'

I'm writing a nodejs view template.
Somewhere I have code like this:
var fnStr = "var moment = require('moment'); moment(new Date);";
var fn = new Function('data', fnStr);
fn();
then, I got error "ReferenceError: require is not defined".
I checked Node API, It says
require isn't actually a global but rather local to each module
Now my own solution is set:
global.require = require;
Any better solutions?

Resources