Organizing code in vanilla js projects using Modules
The main theme of this blog is to learn and avoid mistakes while organizing code into modules.
This blog assumes you have some familiarity with using import and export statements in Javascript frameworks or libraries like Angular and React.
Why do we go for Modules?
Implementing vanilla js in small toy apps is easy because the lines of code are fewer but in applications like eCommerce, and task management apps using vanilla JS there is a lot of code.
Hence, when we have to implement bigger applications like eCommerce using vanilla js, we go for modules.
This helps in..
Code organization
Reusable code
Better understanding and maintenance of code.
Usage of Modules
To begin with, using external scripts as modules in index.html is better for the readability of code.
- To include modules in the codebase, change the script tag in
index.html
<script type="text/javascript" src="./js/index.js"></script>
<!-- instead of the type "text/javascript" change to "module" -->
<script type="module" src="./js/index.js"></script>
<!-- the type "module" mentioned here helps browser identify the script as module -->
Organising the code into modules
While using frameworks, we modularise code into
Components,Pages
etc...Here, we can segregate the code into folder structure based on modules.
Example :
DOM node values
Repeatedly used functions like showing toast and modal, resetting values.
Constants like backend urls.
API calls, that is getting and setting data to backend.
Based on functionality, that is , for example, In to-do app,
authentication
andadd to-do
functionality are independent and can be included in different modules.
Mistakes to be avoided
The order in which modules included in
index.html
matters. Since, the code is executed in the same order.In vanilla js projects, the modules run directly in the browser environment, so, no bare modules are allowed, that is
import { domNodes } from "./domNodes.js";
//this is allowed
import { domNodes } from "./domNodes";
//this is not allowed in simple browser environment.
// "Bare" modules are allowed in React, Node
// Common module system in Node allows usage of relative path or bare modules. Bundlers like Webpack allows this in React.
Conclusion
Modules can be implemented in vanilla js too, with change of type attribute in script.
The order in which modules included matters.
Modules help in code organization, better readability, maintenance of code.
This implementation is without using bundlers in the code.
For learning more about modules, refer to modules.
Subscribe to my newsletter
Read articles from Manasa Mandalreddy directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Manasa Mandalreddy
Manasa Mandalreddy
I record my learnings and experiences as blogs in web development.