Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular, without a browser?

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.

like image 707
Matthew M. Avatar asked Oct 19 '22 04:10

Matthew M.


1 Answers

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.

like image 100
browles Avatar answered Oct 22 '22 00:10

browles