11

Could you use npm modules by using require() in phantomJS? It seems to be able to load javascript files so maybe this is possible?

3
  • 1
    Have you tried doing exactly what you've said? Perhaps you would be pleasantly surprised. Sep 28, 2013 at 16:38
  • can I find an example? it's not loading the npm module for me.
    – KJW
    Sep 30, 2013 at 12:38
  • I just tried importing npm modules using require, can you give me a code sample of what you'be tried? Sep 30, 2013 at 12:40

2 Answers 2

16
+50

That is entirely depends on the nodejs module. It won't work if nodejs module requires some support via native function interface.(npm modules like http, socket.io, will not work on phantomjs, because it dependents on native interfaces)

Pure JavaScript nodejs modules should work on phantomjs too.

2
  • For example, chalk is not usable because it depends on process module.
    – Tien Do
    Mar 2, 2016 at 3:57
  • 1
    Can you provide an example, properly how to inject node module into phantomjs? Answer is obvious by how to make it work, require or injectjs? Feb 27, 2017 at 13:47
4

fyi, phantomjs has an aproximation of commonjs.

you can not use amd modules in phantomjs, and I do not know of any amd loader (like requirejs) that works in phantomjs

Update (2015): I have been using commonjs modules in PhantomJs 1.x and 2.x, they work well with one caveat: you can not use source-mapping (at the bottom of the file, looks like //# sourceMappingURL=index.js.map) as it will cause the PhantomJs module loader to fail. Otherwise, commonjs modules will load normally.

1
  • The sourceMappingUrl comment was my undoing too. Thanks for the tip!
    – Tyson
    Sep 2, 2015 at 23:37

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.