Javascript Build Tools To Toggle Urls/Variables Between Production/Deployment - javascript

I am beginning my first big javascript project! I had a question about deployment. I am using ajax calls to a webservice. To set this up I have a static JS file with code like:
var API_URL_ROOT = 'http://api.example.com/';
var IN_DEVELOPMENT = True;
if (IN_DEVELOPMENT) {
API_URL_ROOT = 'http://localhost.com/api';
}
$.get(API_URL_ROOT)
I am using python/fabric to deploy. I was wondering if there were any prebuilt tools for handling the static analysis/manipulation of the javascript files., Right now it leaves toggling up to the commiters
I was planning on a deployment process like:
issue deploy command
"build" JS, by setting all values to production values (ie. IN_DEVELOPMENT = False)
Minify JS
Deploy code to production servers
I was thinking of just using sed or something to do the IN_DEVELPMENT = False replacement. I have looked at some of the popular minification tools and none seem to offer this sort of functionality.
I would assume that this is a pretty common problem for applications. How is it usually handled? Any help would be appreciated. Thank you
I recently read an article on hackernews from mozilla:
In the Mozilla Persona code base, we frequently expose difficult to
test private functions to the public interface, clearly marking the
extra functions as part of a test API. While other developers are
still able to call these private functions, the author’s intentions
are clear.
...
publicFunction: function() {
return "publicFunction can be invoked externally but "
+ privateFunction();
}
// BEGIN TESTING API
,
privateFunction: privateFunction
// END TESTING API
};
// privateFunction is now accessible via the TESTING API
function privateFunction() {
...
Code between the // BEGIN TESTING API and //END TESTING API
pseudo-markers can be removed for production during the build process.
So other companies are definitely doing this. Are there premade tools to facilitate the JS build proccess that can remove this code? I glanced at a number of their projects on github and didn't see any. Thank you

We are using dojo
And in dojo you can use conditional exclusions for the build version of your js in order to exclude parts of your code that you would not want in your build js. Hope this helps.
eg:
var API_URL_ROOT = 'http://api.example.com/';
//>>excludeStart("dev",!pragmas.dev);
var IN_DEVELOPMENT = True;
//>>excludeEnd("dev");
if (IN_DEVELOPMENT) {
API_URL_ROOT = 'http://localhost.com/api';
}
$.get(API_URL_ROOT)

Related

How can I access the DOM of a <webview> in Electron?

I'm just getting started with Electron, with prior experience with node-webkit (nw.js).
In nw.js, I was able to create iframes and then access the DOM of said iframe in order to grab things like the title, favicon, &c. When I picked up Electron a few days ago to port my nw.js app to it, I saw advice to use webviews instead of iframes, simply because they were better. Now, the functionality I mentioned above was relatively easy to do in nw.js, but I don't know how to do it in Electron (and examples are slim to none). Can anyone help?
Also, I have back/forward buttons for my webview (and I intend on having more than one). I saw in the documentation that I could call functions for doing so on a webview, but nothing I have tried worked either (and, I haven't found examples of them being used in the wild).
I dunno who voted to close my question, but I'm glad it didn't go through. Other people have this question elsewhere online too. I also explained what I wanted to achieve, but w/e.
I ended up using ipc-message. The documentation could use more examples/explanations for the layperson, but hey, I figured it out. My code is here and here, but I will also post examples below should my code disappear for whatever reason.
This code is in aries.js, and this file is included in the main renderer page, which is index.html.
var ipc = require("ipc");
var webview = document.getElementsByClassName("tabs-pane active")[0];
webview.addEventListener("ipc-message", function (e) {
if (e.channel === "window-data") {
// console.log(e.args[0]);
$(".tab.active .tab-favicon").attr("src", e.args[0].favicon);
$(".tab.active .tab-title").html(e.args[0].title);
$("#url-bar").val(e.args[0].url);
$("#aries-titlebar h1").html("Aries | " + e.args[0].title);
}
// TODO
// Make this better...cancel out setTimeout?
var timer;
if (e.channel === "mouseover-href") {
// console.log(e.args[0]);
$(".linker").html(e.args[0]).stop().addClass("active");
clearTimeout(timer);
timer = setTimeout(function () {
$(".linker").stop().removeClass("active");
}, 1500);
}
});
This next bit of code is in browser.js, and this file gets injected into my <webview>.
var ipc = require("ipc");
document.addEventListener("mouseover", function (e) {
var hoveredEl = e.target;
if (hoveredEl.tagName !== "A") {
return;
}
ipc.sendToHost("mouseover-href", hoveredEl.href);
});
document.addEventListener("DOMContentLoaded", function () {
var data = {
"title": document.title,
"url": window.location.href,
// need to make my own version, can't rely on Google forever
// maybe have this URL fetcher hosted on hikar.io?
"favicon": "https://www.google.com/s2/favicons?domain=" + window.location.href
};
ipc.sendToHost("window-data", data);
});
I haven't found a reliable way to inject jQuery into <webview>s, and I probably shouldn't because the page I would be injecting might already have it (in case you're wondering why my main code is jQuery, but there's also regular JavaScript).
Besides guest to host IPC calls as NetOperatorWibby, it is also very useful to go from host to guest. The only way to do this at present is to use the <webview>.executeJavaScript(code, userGesture). This api is a bit crude but it works.
If you are working with a remote guest, like "extending" a third party web page, you can also utilize webview preload attribute which executes your custom script before any other scripts are run on the page. Just note that the preload api, for security reasons, will nuke any functions that are created in the root namespace of your custom JS file when your custom script finishes, however this custodial process will not nuke any objects you declare in the root. So if you want your custom functions to persist, bundle them into a singleton object and your custom APIs will persist after the page fully loads.
[update] Here is a simple example that I just finished writing: Electron-Webview-Host-to-Guest-RPC-Sample
This relates to previous answer (I am not allowed to comment): Important info regarding ipc module for users of Electron 1.x:
The ipc module was split into two separate modules:
ipcMain for the main process
ipcRenderer for the renderer process
So, the above examples need to be corrected, instead of
// Outdated - doesn't work in 1.x
var ipc = require("ipc");
use:
// In main process.
var ipcMain = require('electron').ipcMain
And:
// In renderer process.
var ipcRenderer = require('electron').ipcRenderer
See: http://electron.atom.io/blog/2015/11/17/electron-api-changes section on 'Splitting the ipc module'

Can you share code between multiple grafana scripted dashboards?

I have created a couple of scripted dashboards for Grafana. I'm about to create another. There are all kinds of utility functions that I created and copied from script to script. I would much rather employ good programming practice and import the code rather than copy-paste.
Can that be done? If so, how would one do it?
Yes, this can be done.
This link suggests that SystemJS.import() can be used, although I have not tried it.
This github repo provides a detailed example using a different technique.
Although its not mentioned in the slim Grafana scripted dashboard doc, some version of lodash.com (commit to include lodash) and jquery seem to be available to all scripted dashboards.
The owner of this repo, anryko, has figured out how to use these two libraries to reference your own utility scripts like you're talking about.
All scripted dashboards have a main script; getdash.sh is anryko's main script, as seen by the dash URL on the README.md:
http://grafanaIP/dashboard/script/getdash.js
If you look at the end of getdash.sh, you'll see this line that references code in other user(you)-provided scripts:
var dash = getDashApp(datasources, getDashConf());
For example:
the code for getDashConf() is in this separate .js file
the code for getDashApp() is in this other separate .js file.
Here is the part where getdash.js uses jquery and lodash to load the source files:
// loadScripts :: [scriptSourceStr] -> Promise([jQuery.getScript Result])
var loadScripts = function loadScripts (scriptSrcs) {
var gettingScripts = _.map(scriptSrcs, function (src) {
return $.getScript(src);
});
return Promise.all(gettingScripts);
};
Here is the lodash doc for the above _.map.
The function scriptedDashboard() (also in getdash.js) calls the above loadScripts(), passing it the paths to the source files like this:
loadScripts([
'public/app/getdash/getdash.app.js',
'public/app/getdash/getdash.conf.js'
]).then(function () {
To be honest, I haven't yet looked further under the covers to see how all this makes the utility code 'reference-able.'

Moving created files with JXA

I'm new to JXA scripting, but I'm attempting to troubleshoot some older scripts currently in place here at work. They loop through an InDesign document and create several PDFs based on it. Previously, they would be stored in a folder called "~/PDFExports". However, this doesn't work with 10.10.
If I change the code to just place the PDFs in "~/", it works fine. From there, I'd like to move the files to "~/PDFExports", but I can't seem to find an answer on how to do that. I've seen things about making calls to ObjC, or to call Application('Finder'), but neither work - they both return undefined.
Am I just missing something basic here, or is it really this hard to simply move a file with JXA?
EDIT: Some syntax for how I'm creating the folder in question and how I'm attempting to work with Finder.
//This is called in the Main function of the script, on first run.
var exportFolder = new Folder(exportPath);
if(!exportFolder.exists) {
exportFolder.create();
}
//This is called right after the PDF is created. file is a reference to the
actual PDF file, and destination is a file path string.
function MoveFile(file,destination){
var Finder = Application("Finder");
Application('Finder').move(sourceFile, { to: destinationFolder });
alert("File moved");
}
Adobe apps have long included their own embedded JS interpreter, JS API, and .jsx filename extension. It has nothing to do with JXA, and is not compatible with it.
InDesign's JSX documentation:
http://www.adobe.com/devnet/indesign/documentation.html#idscripting
(BTW, I'd also strongly advise against using JXA for Adobe app automation as it has a lot of missing/broken features and application compatibility problems, and really isn't fit for production work.)
Here's the link to Adobe's InDesign Scripting forum, which is the best place to get help with JSX:
https://forums.adobe.com/community/indesign/indesign_scripting
You could use Cocoa to create the folder
var exportFolder = $.NSHomeDirectory().stringByAppendingPathComponent("PDFExports")
var fileManager = $.NSFileManager.defaultManager
var folderExists = fileManager.fileExistsAtPath(exportFolder)
if (!folderExists) {
fileManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(exportFolder, false, $(), $())
}
and to move a file
var success = fileManager.moveItemAtPathToPathError(sourceFile, destinationLocation, $());
if (success) alert("File moved");
Consider that destinationLocation must be the full path including the file name
and both sourceFile and destinationLocation must be NSString objects like exportFolder
Could it be that the folder is missing ? Could be your reference to the folder object not valid ? Any syntax to show ?
I will share some of what I learned about JXA move and duplicate methods. I am not a professional programmer just an attorney that is passionate about automation. My comments come from much trial and error, reading whatever I could find online, and A LOT of struggle. The move method does not work well with Finder. Use the System Events move method instead. The duplicate method in Finder works just fine. The duplicate method does not work well in system events. This is a modified snippet from a script I wrote showing move() using System Events.
(() => {
const strPathTargetFile = '/Users/bretfarve/Documents/MyFolderA/myFile.txt';
const strPathFolder = '/Users/bretfarve/Documents/MyFolderB/';
/* System Events Objects */
const SysEvents = Application('System Events');
const objPathFolder = SysEvents.aliases[strPathFolder];
SysEvents.move(SysEvents.aliases.byName(strPathTargetFile), {to: objPathFolder});
})();

How to inject variables to Javascript based on environment?

I'm building a javascript application and basically I have three different environments. Local, CI and QA environments. My back-end service is always going to be deployed separately to my front-end application. So, most of the Ajax calls are going to be CORS. We solved this problem already. However, in my code there's something like this.
jQuery.ajax({"url":"http://www.somecompany.com/api"});
So the problem is going to be in CI and QA environments which ajax calls will hit http://ci.somecompany.com/api and http://qa.somecompany.com/api or even http://test.somecompany.com/api. How do I inject those variables based on the environment I'm running. If it's Java or .NET I could use YAML and everything would be ok. But as Javascript it's client-side how do we choose which url to hit based on environments without find and replace in the code or some hacky way. What do people do to overcome this kind of problem generally?
Just a side note, I'm using Knockout.js
If you build your application with grunt then use grunt-variablize. Put your configuration into resources/config.json
{
"test": {
"apiUrl": "http://test.somecompany.com/api"
},
"prod": {
"apiUrl": "http://www.somecompany.com/api"
}
}
configure variablize task:
grunt.initConfig({
/* ... */
variablize: {
target: {
input: "resources/Config.json",
output: "dist/Config.js",
variable: "Config",
property: grunt.option('profile')
}
}
});
run grunt --profile=test, and use it this way:
$(document).ready(function(){
var myURL = Config.apiUrl;
});
This might not be the best way to do it. But this works. :)
You can set value to a javascript variable with your server side code itself.
$(document).ready(function(){
var myURL = "<%=urlFromServer%>"; //Assuming you are using JSP <%= ..%>
});
This global variable holds the value. You can re use this variable wherever you need it.

How can I easily maintain a cross-file JavaScript Library Development Environment

I have been developing a new JavaScript application which is rapidly growing in size.
My entire JavaScript Application has been encapsulated inside a single function, in a single file, in a way like this:
(function(){
var uniqueApplication = window.uniqueApplication = function(opts){
if (opts.featureOne)
{
this.featureOne = new featureOne(opts.featureOne);
}
if (opts.featureTwo)
{
this.featureTwo = new featureTwo(opts.featureTwo);
}
if (opts.featureThree)
{
this.featureThree = new featureThree(opts.featureThree);
}
};
var featureOne = function(options)
{
this.options = options;
};
featureOne.prototype.myFeatureBehavior = function()
{
//Lots of Behaviors
};
var featureTwo = function(options)
{
this.options = options;
};
featureTwo.prototype.myFeatureBehavior = function()
{
//Lots of Behaviors
};
var featureThree = function(options)
{
this.options = options;
};
featureThree.prototype.myFeatureBehavior = function()
{
//Lots of Behaviors
};
})();
In the same file after the anonymous function and execution I do something like this:
(function(){
var instanceOfApplication = new uniqueApplication({
featureOne:"dataSource",
featureTwo:"drawingCanvas",
featureThree:3540
});
})();
Before uploading this software online I pass my JavaScript file, and all it's dependencies, into Google Closure Compiler, using just the default Compression, and then I have one nice JavaScript file ready to go online for production.
This technique has worked marvelously for me - as it has created only one global footprint in the DOM and has given me a very flexible framework to grow each additional feature of the application. However - I am reaching the point where I'd really rather not keep this entire application inside one JavaScript file.
I'd like to move from having one large uniqueApplication.js file during development to having a separate file for each feature in the application, featureOne.js - featureTwo.js - featureThree.js
Once I have completed offline development testing, I would then like to use something, perhaps Google Closure Compiler, to combine all of these files together - however I want these files to all be compiled inside of that scope, as they are when I have them inside one file - and I would like for them to remain in the same scope during offline testing too.
I see that Google Closure Compiler supports an argument for passing in modules but I haven't really been able to find a whole lot of information on doing something like this.
Anybody have any idea how this could be accomplished - or any suggestions on a development practice for writing a single JavaScript Library across multiple files that still only leaves one footprint on the DOM?
The jQuery github has a similar setup to the one you speak of. There is even a Makefile / ant build.xml that use the google closure complier.
The basic concept is to develop all your stuff in separate files, then use cat (or something similar) to put all the files together.
cat intro.js core.js featureOne.js featureTwo.js featureThree.js outro.js > build/script.js
The code inside intro.js and outro.js from jQuery:
// intro.js
(function(window, undefined) {
// outro.js
})(window);
Take a look at how this library is built
http://github.com/oyvindkinsey/easyXDM
The files are separated, but merged together, placed into a closure, and run through jslint by the ant script (build.xml).
The ant script also does conditional 'compilation', string replacements and minification.
I recommend that you split your code base into AMD/RequireJS-style modules.
The AMD format seems to meet most of your requirements, and is rapidly becoming a de facto standard.

Categories

Resources