I'm loading a script from a file, and I'm using eval()
to generate a Javascript code like this:
var code = fs.readFileSync('myfile');
var shiftedCode= 'function(param) {' + code + '}\n'+ '//# sourceURL=myfile';
eval(shiftedCode)
The problem is when I put a breakpoint or debugger inside the code, it stops two lines after the correct one because of the added chars at the beginning I suppose.
Is there a way to shift the sourceURL
to the correct start point may be using sourcemaps?
Thank you in advance for your help.
I see that you're trying to import Javascript code from one page to another and you're facing some problems (You defined one and I will define another one):
Gulp
, Grunt
and Webpack
are made to help you with those use cases and will let you focus on the business logic and keep you away from these kinds of problems. lib
also can help you with your use case. Generate new code first, then run it.var offsetLines = require('offset-sourcemap-lines');
var conv = require('convert-source-map');
var fs = require('fs');
var code = fs.readFileSync('myfile');
var originalMap = conv.fromSource(code).toObject();
var codeBody = conv.removeComments(code);
var offsettedMap = offsetLines(originalMap, 1); // One line to be shifted
var newSourceMapComment = conv.fromObject(offsettedMap).toComment();
var shiftedCode= 'function(param) {\n' + codeBody + '}\n' + newSourceMapComment;
eval(shiftedCode)
eval()
:
eval()
can open a program up to several different injection attacks. The use of eval()
in most contexts can be substituted for a better, alternative approach to a problem.eval()
needlessly!
eval()
is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage/extension. More importantly, third-party code can see the scope in whicheval()
was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.eval()
is also generally slower than the alternatives, since it has to invoke the JS interpreter, while many other constructs are optimized by modern JS engines.
There are safer (and faster!) alternatives toeval()
for common use-cases.
As we agreed, you're trying to import some code. So, why don't you just use one of the modularity systems for Javascript like AMD, RequireJS, CommonJS, ES6 module feature,...
Assume you'll use ES6 modules, it would be very straight forward. You will need to export myfile
script as a module and import it anywhere and that's it
// myfile.js
export function sum (x, y) { return x + y }
// someApp.js
import {sum} from "myfile"
console.log(sum(10, 20));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With