Hi, I want some opinions regarding a change that i want to do. I currently have a library of js (one file) written in ES5. This lib has a main function that behaves as a class and does certain things plus has some utility functions as prototypes. This function is beign called several times (new Lib()). Also lib holds a config object with default values that on class initialization this can change e.g
var lib = new Library();
lib.init({
a: "a",
b: "b"
});
What i want to do is to split the library to different modules and have a main.js that will call the helpers to build the outcome.
My question is now that is it better to do that with ES6? I've seen several implementations on ES6 or ES5 with rollup.
What do you suggest.
Modules are easier to manage - they allow you to have multiple config's in either webpack/rollup and therefore you could have one for production, one for development, one for testing etc.
Using modules also has the added benefit of allows devs to more easily work on sections of code. This means version control is less likely to encounter issues as you wouldn't be working in the same file. @mevrael shows a great example of this. I could work on ModA and you could work on ModB and both commit - no conflict issues and jobs a good un!
I've just concluded the MVP of quite a large project myself, written in ES5, and am in the process of transferring it over to ES6 by utilising modules + import/export.
You should write ES6 these days! ES6 does not only add class sugar, but many many other sweet advantages which will make your life a lot easier :)
As for the question "shall i stick with function way or shall i move to classes", though, I think it's personal taste. You can go the functional way and just put all your functions on a single object which you import from some module. Or you can go the OO way and write classes, which bring a number of advantages (like Mixins) and a number of complications.
Personally, I prefer the OO way, because I like to bundle my data into instances and couple that with procedures. I also like to compose my APIs with Mixins. So OO, for me, is the right way to go in most situations. Don't forget: use the right tool for the right job. Sometimes, it does not make a whole lot of sense to make a class, and just writing the functions is way better.
Mev-Rael
Executive Product Leader & Mentor for High-End Influencers and Brands @ mevrael.com
Use Rollup to bundle your ES6 modules into single app.js
Module A
export const ModuleAConfig = { a: 'a', b: 'b' }; export const ModuleA = { Config: ModuleAConfig, init(node) { ... }, ... };app.js:
import { ModuleA, ModuleAConfig } from './components/ModuleA'; Object.assign(ModuleAConfig, { a: 'newA', b: 'newB' }); ModuleA.init();You can find more examples in BunnyJS src or any ES6 library. If you will have any questions about Vanilla JS/ES6 architecture, let me know by mentioning with @.