Vanilla Javascript
Vanilla Javascript is Javascript with no or minimal external frameworks.
Modules
One way to avoid the monolithic Javascript files that can occur when not using frameworks is to utilize Javascript modules and the import
/export
syntax. For instance, if you wanted to put a function into an external file and import that in as a module, there are a few steps you have to take. Let's use an example:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="index.js"></script>
</body>
</html>
index.js
const greeting = (name) => {
return `Hello, my name is ${name}!`;
};
["Bob", "Jane"].forEach(name => {
console.log(greeting(name));
});
If we wanted to use modules for this to separate the greeting
function to another file, we need to do the following things:
- Move relevant code into external files.
- Put
export
instructions into the new external files. - Put
import
instructions in the top of the file we want the external code to reside in. - Add script tags into our HTML to load all our scripts on page load (you may not need the ones being imported in another file if they are locally accessible).
- Make our scripts into modules by adding
type="module"
to all of our interactingscript
tags.
If we do this to the earlier example, we end up with the following:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<!-- You no longer need `greeting.js` import-->>
<script src="index.js" type="module"></script>
</body>
</html>
greeting.js
const greeting = (name) => {
return `Hello, my name is ${name}!`;
};
export default greeting;
index.js
import greeting from './greeting.js';
["Bob", "Jane"].forEach(name => {
console.log(greeting(name));
});
Different Import/Export Strategies
If using export default
, then we can just import
the function without need for curly braces. If we however use named exports, we have to do things a little differently[3].
external.js
// ...
export {
function1,
function2
};
index.js
import { function1, function2 } from './external.js';
References
- Testing Vanilla Javascript
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#default_exports_versus_named_exports
Last modified: 202401040446