I'm trying to have the ability to put Javascript code within strings (inside Javascript). I'm using my own gruntjs task to read all the javascript files and place it within strings.
var modules = [];
modules['filename.js'] = "code here...."
This works for simple Javascript classes, but when putting external libraries in such format (JQuery, Ember.js, Underscore) it will fail. I am replacing each " inside the code to \". But I'm still getting syntax errors. I'm thinking it may have to do with some RegEx, or, in some parts they might have escaped some double quotes.
Edit: The code is found here: https://github.com/TheHydroImpulse/resolve.js But specifically the build script (gruntjs) is here: https://github.com/TheHydroImpulse/resolve.js/blob/master/examples/basic/grunt.js
Any Suggestions?
-
Have you tried encoding/decoding the content of the JS files?Alexis Pigeon– Alexis Pigeon2012年10月30日 21:49:36 +00:00Commented Oct 30, 2012 at 21:49
-
In what sense? Meaning UTF8 or something?Daniel– Daniel2012年10月30日 21:54:12 +00:00Commented Oct 30, 2012 at 21:54
-
Maybe base64 or similar?Tyilo– Tyilo2012年10月30日 21:54:42 +00:00Commented Oct 30, 2012 at 21:54
-
No, I mean using encoreURIComponent / decodeURIComponentAlexis Pigeon– Alexis Pigeon2012年10月30日 21:56:49 +00:00Commented Oct 30, 2012 at 21:56
-
Would this not render special characters useless? Or would I have to re-encode before using the contents of the stringified code?Daniel– Daniel2012年10月30日 21:58:35 +00:00Commented Oct 30, 2012 at 21:58
2 Answers 2
In order to keep intact the JS code, you'll have to encode it before storing it to a string, and decode the string before using it.
Both operations can be carried out with built-in JavaScript functions encodeURIComponent() and decodeURIComponent()
Comments
Wild stab in the dark here (just became halloween here under an hour ago) but maybe you are not putting it all into one line, and therefore not handling multiline strings correctly...
Or maybe you are crushing the files into one line, and not adding semi-colons where necessary.
I recommend you use a tool for minifying, like uglify and then try it with the libraries as a single line of minified javascript.