Search code examples
javascriptnode.jsmodulebrowser-console

Writing JS code for both browser and node


Being relatively new to programming in general, the code I usually write in JS isn't very complex. I have never felt the need to segment it into smaller chunks that would be easier to manage, until now.
I would always use the approach of using a single file with a single object

const mymodule = {
    feature: function(){...},
    submodule: {
        property: 5,
        ...
    }
}

I would then simply load it in html. For debugging I used the browser console.
But recently I've installed nodeJS and learned about the system of modules and I thought that was exactly what I need for my current project. So far I coded it using the technique shown above, but that is now hard to manage. Scrolling through one giant messy js file is quite frustrating. I also realized that maybe I'd like to use this project in node as well, so modules would really help I thought.

On MDN Docs I learned that modules can also be used in the browser, which made me very happy, until I realized that in the browser they cannot be run locally, but rather only through http(s) - served (meaning I cannot use my favourite chrome console for debugging 😔). But if the module system is the same as in nodeJS, than I could use node to still run and test the project locally!

However, I can't figure out how I could work with modules so that they could be used both in the browser and in node. For example the confusing ways of requiring, importing and exporting (export x exports = x module.exports = ).
I am aware of some older questions similar to mine, but they are very old. Since modules are now literally a part of web standarts, I really hoped there would be a simple way to do this without the need for any external tools.

If you can point me in the right direction or show an example of writing a module that can run in both enviroments, that would be great.


Solution

  • You can use web bundlers for this case. Something like snowpack will allow you to use nodejs modules that locally installed by running snowpack dev. It will provide you local web server and opens browser window with your page automaticly, that also allows you to use MDN examples.