How to write modules compatible with both nodejs and the browser?

I am writing a node module {module set}, and in the future this may be ported to the browser environment. For this reason, I am looking for programming methods that will allow me to write the code once, and then reuse the same, maybe if this requires some kind of working assembly, its fine.

Well, if it's a workflow,

  • write node modules
  • run some build script that converts the above written code into a single js file to be able to run in a browser environment.

Please do not offer me a browser.

Why is there no browser or other similar material? I saw the code that was generated. It was huge and had a lot of browser code entered. I found it difficult to troubleshoot and go through the code I wrote

+4
source share
2 answers

I really recommend taking a look at Browserify again. Other than that, add the Universal Module Definition (UMDJS) exporter to your files. This will allow you to expose your modules in node, browser, requirejs / amd or just fit in a script tag on any site.

You can also use the module transpiler - write to the exporter of the ES6 module and ask him to convert for use in the browser, or commonjs / node.

0
source

Well, Darren , consider that I have some Agent object that will require XMLHttpRequest for its transport layer on the browser side, but use the NodeJS ' http API server.

Where do you make the switch, for example using Grunt? Let's say we have the following files: Agent.js , transport-browser.js and transport-node.js . Maybe I'm learning from your technique, but thatโ€™s what I would like (Iโ€™m thinking about all this now).

0
source

Source: https://habr.com/ru/post/1494650/


All Articles