Sometimes I want to experiment (in a local Node script) with some aspect of Angular - e.g. Services, DI, etc - stuff that has nothing to do with the Browser or the DOM. Is there a way to do that? i.e. load some base portion of the Angular Infrastructure? If I just require("angular") in a Node script, it complains:
ReferenceError: window is not defined
which makes sense because Angular lives for the Browser-window.
But it seems like some portions of Angular could be used for non-web applications - although that's not my reason for asking this. I'm just trying to improve my understanding Angular and sometimes want to do a little experiment while stripping away/ignore as much as possible.
Experimenting with Angular is best done in a browser, due to window
and other API's Angular relies on.
However, if you're dead set on using Angular with node, you might look into the vm
module which essentially lets you eval
code with a specific stand-in object as a sort of proxy global object. e.g.:
const vm = require('vm');
const fs = require('fs');
const test = fs.readFileSync('./test.js', 'utf-8');
const windowProxy = {
document: {
createElement: function() {
return {
setAttribute: function() {},
pathname: ''
}
},
querySelector: function() {},
addEventListener: function() {}
},
location: {
href: ''
},
addEventListener: function() {}
};
windowProxy.window = windowProxy;
vm.createContext(windowProxy);
vm.runInContext(test, windowProxy);
will at least let you load Angular without complaining. Undoubtedly you would encounter more errors, and would have to polyfill the missing browser API's yourself.
You might also look into PhantomJS for a more robust testing environment, though that would no longer be Node.
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