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:

  1. Move relevant code into external files.
  2. Put export instructions into the new external files.
  3. Put import instructions in the top of the file we want the external code to reside in.
  4. 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).
  5. Make our scripts into modules by adding type="module" to all of our interacting script 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

  1. Testing Vanilla Javascript
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
  3. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#default_exports_versus_named_exports

Last modified: 202401040446