5

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.

2
  • 3
    sandboxes like plunker are ideal since they live reload as you write and can set a new app up in seconds Commented Aug 24, 2015 at 0:15
  • Angular doesn't work without a browser. This is something they are planning to address (I read somewhere) for non-browser clients that run JS, but not yet Commented Aug 24, 2015 at 0:23

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.