I am working on modularizing the scripts. Consider the following project hierarchy.
My files look like this
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Learn EcmaScript</title>
<script src="script.js" type="module" defer></script>
</head>
<body></body>
</html>
script.js
import math from './scripts/math.js';
console.log("3 + 4 = ", math.add(3, 4));
scripts/math.js
import { add } from './add.js';
import { subtract } from './subtract.js';
import { multiply } from './multiply.js';
import { divide } from './divide.js';
export default {
add,
subtract,
multiply,
divide,
};
scripts/add.js
export const add = (x, y) => Number(Number(x) + Number(y));
scripts/subtract.js
export const subtract= (x, y) => Number(Number(x) - Number(y));
scripts/multiply.js
export const multiply= (x, y) => Number(Number(x) * Number(y));
scripts/divide.js
export const divide = (x, y) => Number(Number(x) / Number(y));
When I run the code using live server – the output is fine.
My concern here is related to the application performance.
I am using only math.add()
and I need only add.js
to be loaded. Rest of the scripts (i.e., subtract.js
, multiply.js
, divide.js
) are unnecessary here. But in the chrome dev tools I can see all of the scripts loading.
I tried to use Dynamic import
syntax and modified the math.js
file as below
math.js
export default {
add: () => import('./add.js').then((m) => m.add),
subtract: () => import('./subtract.js').then((m) => m.subtract),
multiply: () => import('./multiply.js').then((m) => m.multiply),
divide: () => import('./divide.js').then((m) => m.divide),
};
then the output is like below
Though the scripts are loaded on demand, I am unable to get the output properly. How could I do the code refactor here to get proper output with on demand script load?
(Let’s consider only the default export scenario)