Node-Red Editor and Library dependencies? - javascript

I'm in the process to create my first Node-RED contribution. The node will clean an incoming object based on a sample object provided in the editor. I'm using the RED.editor and the RED.library.
I'm wondering if I need to declare a dependency in my package file. Currently it looks like this:
{
"name" : "node-red-contrib-objectcleaner",
"version" : "0.0.1",
"description" : "Removes properties from incoming (payload) object, that are not in a template object",
"dependencies": { /*Do I need anything here? */
},
"keywords": [ "node-red", "validation", "flow" ],
"node-red" : {
"nodes": {
"objectcleaner": "objectcleaner/objectcleaner.js"
}
}
}
What, if anything, goes into the dependencies? I know I will put node.js dependencies there, but do I need to list the editor/library?

You'll probably do better asking questions like this on the mailing list here:
https://groups.google.com/forum/#!forum/node-red
You shouldn't need to list Node-RED in the dependencies as this will just pull in another copy into the node_modules tree.
You should be fine just using the reference to RED object that is passed in when the node is initialised

Related

How to load all dependency of urijs by rquirejs config?

I want to include this library for use https://github.com/medialize/URI.js/tree/master
I have added it to bower.json
{
"name": "my-project",
"version": "1.0.0",
"dependencies": {
"urijs": "~1.16.1"
}
...
}
When I load my project in a browser, I got these error:
These scripts are all part of the urijs project. You can find them here: https://github.com/medialize/URI.js/tree/master/src
I would like to be able to resolve by requirejs configuration alone with minimal change (i.e. hopefully do not need to specify each dependent script indiviudally). What is the easiest way to define the dependency?
Is it possible? If so, how?
At the end I can resolve it by creating the final artefact and hosted the outcome in a forked project. I am hoping for a more elegant and/or simpler solution.
Looks like URI.js sets up a universal module loader that should work with RequireJS. It doesn't look like you have to reference every script in your config. Make your RequireJS config file look like their readme.md:
require.config({
paths: {
urijs: 'where-you-put-uri.js/src'
}
});
require(['urijs/URI'], function(URI) {
console.log("URI.js and dependencies: ", URI("//amazon.co.uk").is('sld') ? 'loaded' : 'failed');
});
require(['urijs/URITemplate'], function(URITemplate) {
console.log("URITemplate.js and dependencies: ", URITemplate._cache ? 'loaded' : 'failed');
});

Grunt Concat same file multiple times

I'd like to use grunt-contrib-concat for application frontend HTML templating purposes and this would be useful for me.
I'd like to define page partials and and concatenate them inside an output file that is going to be compiled by handlebars.
I've got everything set up, however Concat doesn't allow me to use the same file more than once.
Basically concat is filtering the sources so they don't occur more than once. The second partial1.hbs will not be concatenated.
pageconcat: {
src: [
'app/templates/partial1.hbs',
'app/templates/partial2.hbs',
'app/templates/partial1.hbs'
],
dest: 'app/result.hbs'
}
Is there any way to do this?
Update 1
After playing around with grunt's console output function, I was able to debug (of some sort) the concat plugin. Here's what I found out: The input array is deduplicated by grunt for some reason.
Update 2
The deduplication occurs in the foreach file loop that grunt uses. I've managed to bypass that (see answer). I do not know how reliable my solution is but it's a workaround and it works well if you don't put the wrong input.
You may be able to use the file array format to set up two different source sets. Something like this:
{
"files": [{
"src": [
"app/templates/partial1.hbs",
"app/templates/partial2.hbs"
],
"dest": "app/result.hbs"
}, {
"src": [
"app/result.hbs",
"app/templates/partial1.hbs"
],
"dest": "app/result.hbs"
}]
}
added "app/result.hbs" to second source set, as was pointed out in the comments.
Thanks.
Solution
After some debugging I came up with a solution. Certainly not the best, but it works fine, as it should.
I edited the concat.js plugin file inside the node_modules folder the following way:
grunt.registerMultiTask('concat', ...){
var self = this;
//several lines of code
//...
//replace f.src.filter(..) wtih
self.data.src.filter(..);
}

Configure a generic jQuery plugin with Browserify-shim?

I'm using browserify-shim and I want to use a generic jQuery plugin. I have looked over the Browserify-shim docs multiple times and I just can't seem to understand what's going on and/or how it knows where to put plugins, attach to the jQuery object etc. Here's what my package.json file looks like:
"browser": {
"jquery": "./src/js/vendor/jquery.js",
"caret": "./src/js/vendor/jquery.caret.js"
},
"browserify-shim": {
"caret": {
"depends": ["jquery:$"]
}
}
According the the example given on the browserify-shim documentation, I don't want to specify an exports because this plugin (and most if not all jQuery plugins) attach themselves to the jQuery object. Unless I'm doing something wrong above, I don't understand why it doesn't work (I get an error telling me the function is undefined) when I use it. See below:
$('#contenteditable').caret(5); // Uncaught TypeError: undefined is not a function
So my question is, how does one configure a generic jQuery plugin (which attaches itself to the jQuery object) with browserify and browserify-shim?
After revisiting this and trying some more things, I finally wrapped my head around what browserify-shim is doing and how to use it. For me, there was one key principle I had to grasp before I finally understood how to use browserify-shim. There are basically two ways to use browserify-shim for two different use cases: exposing & shimming.
Background
Let's say you want to just drop in a script tag in your markup (for testing or performance reasons like caching, CDN & the like). By including a script tag in the markup the browser will hit the script, run it, and most likely attach a property on the window object (also known as a global in JS). Of course this can be accessed by either doing myGlobal or window.myGlobal. But there's an issue with either syntax. It doesn't follow the CommonJS spec which means that if a module begins supporting CommonJS syntax (require()), you're not able to take advantage of it.
The Solution
Browserify-shim allows you to specify a global you'd like "exposed" through CommonJS require() syntax. Remember, you could do var whatever = global; or var whatever = window.global; but you could NOT do var whatever = require('global') and expect it to give you the right lib/module. Don't be confused about the name of the variable. It could be anything arbitrary. You're essentially making a global variable a local variable. It sounds stupid, but its the sad state of JS in the browser. Again, the hope is that once a lib supports CommonJS syntax it will never attach itself via a global on the window object. Which means you MUST use require() syntax and assign it to a local variable and then use it wherever you need it.
Note: I found variable naming slightly confusing in the browserify-shim docs/examples. Remember, the key is that you want to include a lib as if it were a properly behaving CommonJS module. So what you end up doing is telling browserify that when you require myGlobal require('myGlobal') you actually just want to be given the global property on the window object which is window.myGlobal.
In fact, if you're curious as to what the require function actually does, it's pretty simple. Here's what happens under the hood:
var whatever = require('mygGlobal');
becomes...
var whatever = window.mygGlobal;
Exposing
So with that background, let's see how we expose a module/lib in our browserify-shim config. Basically, you tell browserify-shim two things. The name you want it accessible with when you call require() and the global it should expect to find on the window object. So here's where that global:* syntax comes in. Let's look at an example. I want to drop in jquery as a script tag in index.html so I get better performance. Here's what I'd need to do in my config (this would be in package.json or an external config JS file):
"browserify-shim": {
"jquery": "global:$"
}
So here's what that means. I've included jQuery somewhere else (remember, browserify-shim has no idea where we put our tag, but it doesn't need to know), but all I want is to be given the $ property on the window object when I require the module with the string parameter "jquery". To further illustrate. I could also have done this:
"browserify-shim": {
"thingy": "global:$"
}
In this case, I'd have to pass "thingy" as the parameter to the require function in order to get an instance of the jQuery object back (which it's just getting jQuery from window.$):
var $ = require('thingy');
And yes, again, the variable name could be anything. There's nothing special about $ being the same as the global property $ the actual jQuery library uses. Though it makes sense to use the same name to avoid confusion. This ends up referencing the the $ property on the window object, as selected by the global:$ value in the browserify-shim object in package.json.
Shimming
Ok, so that pretty much covers exposing. The other main feature of browserify-shim is shimming. So what's that? Shimming does essentially the same thing as exposing except rather than including the lib or module in HTML markup with something like a script tag, you tell browserify-shim where to grab the JS file locally. There's no need to use the global:* syntax. So let's refer back to our jQuery example, but this time suppose we are not loading jQuery from a CDN, but simply bundling it with all the JS files. So here's what the config would look like:
"browser": {
"jquery": "./src/js/vendor/jquery.js", // Path to the local JS file relative to package.json or an external shim JS file
},
"browserify-shim": {
"jquery": "$"
},
This config tells browserify-shim to load jQuery from the specified local path and then grab the $ property from the window object and return that when you require jQuery with a string parameter to the require function of "jquery". Again, for illustrative purposes, you can also rename this to anything else.
"browser": {
"thingy": "./src/js/vendor/jquery.js", // Path to the local JS file relative to package.json or an external shim JS file
},
"browserify-shim": {
"thingy": "$"
},
Which could be required with:
var whatever = require('thingy');
I'd recommend checking out the browserify-shim docs for more info on the long-hand syntax using the exports property and also the depends property which allows you to tell browserify-shim if a lib depends on another lib/module. What I've explained here applies to both.
Anonymous Shimming
Anonymous shimming is an alternative to browserify-shim which lets you transform libs like jQuery into UMD modules using browserify's --standalone option.
$ browserify ./src/js/vendor/jquery.js -s thingy > ../dist/jquery-UMD.js
If you dropped that into a script tag, this module would add jQuery onto the window object as thingy. Of course it could also be $ or whatever you like.
If however, it's requireed into your browserify'd app bundle, var $ = require("./dist/jquery-UMD.js");, you will have jQuery available inside the app without adding it to the window object.
This method doesn't require browserify-shim and exploits jQuery's CommonJS awareness where it looks for a module object and passes a noGlobal flag into its factory which tells it not to attach itself to the window object.
For everyone, who is looking for a concrete example:
The following is an example of package.json and app.js files for a jQuery plugin that attaches itself to the jQuery/$ object, e.g.: $('div').expose(). I don't want jQuery to be a global variable (window.jQuery) when I require it, that's why jQuery is set to 'exports': null. However, because the plugin is expecting a global jQuery object to which it can attach itself, you have to specify it in the dependency after the filename: ./jquery-2.1.3.js:jQuery. Furthermore you need to actually export the jQuery global when using the plugin, even if you don't want to, because the plugin won't work otherwise (at least this particular one).
package.json
{
"name": "test",
"version": "0.1.0",
"description": "test",
"browserify-shim": {
"./jquery-2.1.3.js": { "exports": null },
"./jquery.expose.js": { "exports": "jQuery", "depends": [ "./jquery-2.1.3.js:jQuery" ] }
},
"browserify": {
"transform": [
"browserify-shim"
]
}
}
app.js
// copy and delete any previously defined jQuery objects
if (window.jQuery) {
window.original_jQuery = window.jQuery;
delete window.jQuery;
if (typeof window.$.fn.jquery === 'string') {
window.original_$ = window.$;
delete window.$;
}
}
// exposes the jQuery global
require('./jquery.expose.js');
// copy it to another variable of my choosing and delete the global one
var my_jQuery = jQuery;
delete window.jQuery;
// re-setting the original jQuery object (if any)
if (window.original_jQuery) { window.jQuery = window.original_jQuery; delete window.original_jQuery; }
if (window.original_$) { window.$ = window.original_$; delete window.original_$; }
my_jQuery(document).ready(function() {
my_jQuery('button').click(function(){
my_jQuery(this).expose();
});
});
In the above example I didn't want my code to set any globals, but I temporarily had to do so, in order to make the plugin work. If you only need jQuery, you could just do this and don't need any workaround: var my_jQuery = require('./jquery-2.1.3.js'). If you are fine with your jQuery being exposed as a global, then you can modify the above package.json example like so:
"browserify-shim": {
"./jquery-2.1.3.js": { "exports": "$" },
"./jquery.expose.js": { "exports": null, "depends": [ "./jquery-2.1.3.js" ] }
Hope that helps some people, who were looking for concrete examples (like I was, when I found this question).
Just for completeness, here is a method that exploits jQuery's CommonJS awareness to avoid having to worry about polluting the window object without actually needing to shim.
Features
jQuery included in the bundle
plugin included in the bundle
no pollution of the window object
Config
In ./package.json, add a browser node to create aliases for the resource locations. This is purely for convenience, there is no need to actually shim anything because there is no communications between the module and the global space (script tags).
{
"main": "app.cb.js",
"scripts": {
"build": "browserify ./app.cb.js > ./app.cb.bundle.js"
},
"browser": {
"jquery": "./node_modules/jquery/dist/jquery.js",
"expose": "./js/jquery.expose.js",
"app": "./app.cb.js"
},
"author": "cool.blue",
"license": "MIT",
"dependencies": {
"jquery": "^3.1.0"
},
"devDependencies": {
"browserify": "^13.0.1",
"browserify-shim": "^3.8.12"
}
}
Method
Because jQuery is CommonJS-aware these days, it will sense the presence of the module object provided by browserify and return an instance, without adding it to the window object.
In the app, require jquery and add it to the module.exports object (along with any other context that needs to be shared).
Add a single line at the start of the plugin to require the app to access the jQuery instance it created.
In the app, copy the jQuery instance to $ and use jQuery with the plugin.
Browserify the app, with default options, and drop the resulting bundle into a script tag in your HTML.
Code
app.cb.js
var $ = module.exports.jQuery = require("jquery");
require('expose');
$(document).ready(function() {
$('body').append(
$('<button name="button" >Click me</button>')
.css({"position": "relative",
"top": "100px", "left": "100px"})
.click(function() {
$(this).expose();
})
);
});
at the top of the plugin
var jQuery = require("app").jQuery;
in the HTML
<script type="text/javascript" src="app.cb.bundle.js"></script>
Background
The pattern used by jQuery is to call it's factory with a noGlobal flag if it senses a CommonJS environment. It will not add an instance to the window object and will return an instance as always.
The CommonJS context is created by browserify by default. Below is an simplified extract from the bundle showing the jQuery module structure. I removed the code dealing with isomorphic handling of the window object for the sake of clarity.
3: [function(require, module, exports) {
( function( global, factory ) {
"use strict";
if ( typeof module === "object" && typeof module.exports === "object" ) {
module.exports = factory( global, true );
} else {
factory( global );
}
// Pass this if window is not defined yet
} )( window, function( window, noGlobal ) {
// ...
if ( !noGlobal ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}) );
}, {}]
The best method I found is to get things working in the node module system and then it will work every time after browserify-ing.
Just use jsdom to shim the window object so that the code is isomorphic. Then, just focus on getting it to work in node. Then, shim any traffic between the module and global space and finally browserify it and it will just work in the browser.
I was using wordpress. Hence, I was kind of forced to use the wordpress core's jQuery, available in window object.
It was generating slick() not defined error, when I tried to use slick() plugin from npm. Adding browserify-shim didn't help much.
I did some digging and found out that require('jquery') was not consistent always.
In my theme javascript file, it was calling the wordpress core's jquery.
But, in slick jquery plugin it was calling the latest jquery from node modules.
Finally, I was able to solve it. So, sharing the package.json and gulpfile configuration.
package.json:
"browserify": {
"transform": [
"browserify-shim"
]
},
"browserify-shim": {
"jquery": "global:jQuery"
},
gulpfile.babel.js:
browserify({entries: 'main.js', extensions: ['js'], debug: true})
.transform(babelify.configure({
presets: ["es2015"]
}))
.transform('browserify-shim', {global: true})
Doing transform 'browserify-shim' was crucial part, I was missing earlier. Without it browserify-shim was not consistent.

Trying to create a Meteor Package

I've been trying to create a Smart Package for the SkelJS framework.
The file is being loaded by the browser but when I try and access the object it exports it says its undefined. I'm using the following code in package.js:
Package.describe({
summary: "SkelJS for Meteor"
});
Package.on_use(function (api) {
api.use('jquery', 'client');
api.add_files(['skel.js'], 'client');
api.export('skel', 'client');
});
Also trying to access Package.skeljs.skel returns undefined as well.
In smart.json I'm using:
{
"name": "skeljs",
"description": "SkelJS for Meteor",
"homepage": "",
"author": "Giles Butler (http://giles.io)",
"version": "0.1.0",
"git": ""
}
I know SkelJS has been loaded because it logs to the console no configuration detected, waiting for manual init but then when I try and run skel.init() it returns undefined.
Any help or tips would be really appreciated.
Thanks
Giles
You also need to modify the first line of skel.min.js/skel.js
Within packages variable scoping still applies so you have to remove the var keyword if you want the file to let other files (such as package.js for api.export) access its variables.
The fix would be to change:
var skel=function() ....
to
skel=function() ....

Updating file references in a json file via a grunt task

I'm a JavaScript developer and fairly new to creating a build process from scratch. I chose to use Grunt for my current project and have created a GruntFile that does about 90% of what I need it to do and it works great, except for this one issue. I have several JavaScript files that I reference while I'm developing a chrome extension in the manifest.json file. For my build process I am concatenating all of these files and minifying it into one file to be included in manifest.json. Is there anyway to update the file references in the manifest.json file during the build process so it points to the minified version?
Here is a snippet of the src manifest file:
{
"content_scripts": [{
"matches": [
"http://*/*"
],
"js": [
"js/lib/zepto.js",
"js/injection.js",
"js/plugins/plugin1.js",
"js/plugins/plugin2.js",
"js/plugins/plugin3.js",
"js/injection-init.js"
]
}],
"version": "2.0",
}
I have a grunt task that concatenates and minifies all the js files listed above into one file called injection.js and would like a grunt task that can modify the manifest file so it looks like this:
{
"content_scripts": [{
"matches": [
"http://*/*"
],
"js": [
"js/injection.js"
]
}],
"version": "2.0",
}
What I've done for now is have 2 versions of the manifest file, one for dev and one for build, during the build process it copies the build version instead. This means I need to maintain 2 versions which I'd rather not do. Is there anyway to do this more elegantly with Grunt?
Grunt gives its own api for reading and writing files, i feel that better than other dependencies like fs:
Edit/update json file using grunt with command grunt updatejson:key:value after putting this task in your gruntjs file
grunt.registerTask('updatejson', function (key, value) {
var projectFile = "path/to/json/file";
if (!grunt.file.exists(projectFile)) {
grunt.log.error("file " + projectFile + " not found");
return true;//return false to abort the execution
}
var project = grunt.file.readJSON(projectFile);//get file as json object
project[key]= value;//edit the value of json object, you can also use projec.key if you know what you are updating
grunt.file.write(projectFile, JSON.stringify(project, null, 2));//serialize it back to file
});
I do something similar - you can load your manifest, update the contents then serialize it out again. Something like:
grunt.registerTask('fixmanifest', function() {
var tmpPkg = require('./path/to/manifest/manifest.json');
tmpPkg.foo = "bar";
fs.writeFileSync('./new/path/to/manifest.json', JSON.stringify(tmpPkg,null,2));
});
I disagree with the other answers here.
1) Why use grunt.file.write instead of fs? grunt.file.write is just a wrapper for fs.writeFilySync (see code here).
2) Why use fs.writeFileSync when grunt makes it really easy to do stuff asynchronously? There's no doubt that you don't need async in a build process, but if it's easy to do, why wouldn't you? (It is, in fact, only a couple characters longer than the writeFileSync implementation.)
I'd suggest the following:
var fs = require('fs');
grunt.registerTask('writeManifest', 'Updates the project manifest', function() {
var manifest = require('./path/to/manifest'); // .json not necessary with require
manifest.fileReference = '/new/file/location';
// Calling this.async() returns an async callback and tells grunt that your
// task is asynchronous, and that it should wait till the callback is called
fs.writeFile('./path/to/manifest.json', JSON.stringify(manifest, null, 2), this.async());
// Note that "require" loads files relative to __dirname, while fs
// is relative to process.cwd(). It's easy to get burned by that.
});

Categories