How do I divide JavaScript into multiple javascript files & minify?

Hi everyone,

I am building a website which requires a lot of JavaScript and my index.js file is getting too big. I have thought about dividing the code into multiple javascript files and importing them all through the script tag, but that doesn’t feel optimal. I thought of using the module approach. I am following the Mozilla documentation about JavaScript modules. However – if I try to write my JavaScript like this, my console throws up the following error:

/assets/js/index.js:208 Uncaught SyntaxError: Cannot use import statement outside a module

I have tried adding the type="module" property to my script tags but that didn’t seem to work. Can somebody help point out where I am going wrong?

Additionally – this is my first huge project, it’s for a client and thus I want to follow the best practises for web development. How would I minify my CSS or JavaScript files? Can I use npm with kirby?

Thank you in advance! All help is truly appreciated.

How would I minify my CSS or JavaScript files? Can I use npm with kirby?

Sure, you can use NPM!
For css I would have a look at postcss, minify plugin.

I’m sure there are also equivalent solutions for javascript.

Edit:
This tutorial helped me a lot:

If you want an advanced setup and already have composer in use, I recommend getting Vite, as it cleverly does all that for you under the hood.

Then, how you split up your files is a bit up to you. I often use async imports (await import('...')) with some conditional checks in my JavaScript files, and only load one index file. Vite creates logical junks. But there are other approaches.