Using ES6 modules in the browser.
So far you have used modules import/export
in NodeJS and in the front-end you have used script
tags to import your source code.
You can actually use modules in your front end code. And frameworks like ReactJS & VueJS are heavily using that. To do that though you will need a tool that convert the JavaScript that is using modules into JavaScript that can be executed in the browser.
What you will basically start doing is to write NodeJS like JavaScript for your front-end. This code will then be transpiled (converted) into JavaScript which can execute in the browser. NodeJS code can't reliably be used in the browser.
You will be using ViteJS as a front-end build tool. ViteJS will also start up a webserver to use for front-end development.
Deploying front-end code using ViteJS
is a bit more complex that just creating an index.html
file with a bunch from css
& js
file.
But it comes with a lot of benefits that comes with the usage of using modules & other advanced JS features.
To start using ViteJS you can follow these instructions.
We will try this out by using a small fruits dataset:
const fruits = [
{
pic : "π",
qty : 7
},
{
pic : "π"
qty: 34
},
{
pic : "π",
qty : 16
}
]
We will create a small widget that shows a fruit with a counter for the quantity of that fruit available. We will add filter support to show fruits with at least a given quantity available.
Here are more emojis if you wanna add more data : πππ₯ππ
You will need to create a project using ViteJS called fruit-filter
.
Use the npm create vite@latest
command.
Choose all the Vanilla options and follow the prompts.
Change into the fruit-filter
project & open it in VS Code.
Start the project with npm run dev
.
You will notice there are quite a few files there already.
You will be working in main.js
, index.html
& style.css
mainly.
Note the import statements on top of the main.js
file:
import './style.css'
import javascriptLogo from './javascript.svg'
import viteLogo from '/vite.svg'
You can remove the svg
imports and only keep the css
import.
To have something like this:
import './style.css'
Next create a file called fruits.js in there we will create a factory function called FruitFilter
and export it.
export default function FruitFilter() {
}
Import it in main.js
using import FruitFilter from "FruitFilter";
And create an instance like this: const fruitFilter = FruitFilter();
Save all the changes. Nothing should happen in the browser, but there should be no errors the Developer Console
.