r/programming • • Apr 29 '21

Modern JavaScript Explained For Dinosaurs

https://medium.com/the-node-js-collection/modern-javascript-explained-for-dinosaurs-f695e9747b70
287 Upvotes

172 comments sorted by

View all comments

62

u/sylvanelite Apr 30 '21

It's worth noting that since this was written, javascript modules now exist in the browser, so you can write models kinda like in the article, without using the command line tools.

But annoyingly, there's some quirks. They syntax isn't the same as in the article. For example:

var moment = require('moment');

can be replaced with something like:

import moment from 'moment';

And if doing it the "dinosaur" way, instead of having javascript files like:

<script type="text/javascript" src="file.js" ></script>

you can do something like:

<script type="module" src="module.mjs"></script>

14

u/if-loop Apr 30 '21

Ok, but if module.mjs imports other modules, aren't those downloaded automatically and separately (with dozens of requests since there is no bundling)?

22

u/sylvanelite Apr 30 '21

Yeah that's right. If you want to bundle the files you'll still need tooling like mentioned in the article.

The main thing is that the "import" syntax won't work in a browser without <script type="module"> which is a fairly obscure gotcha for people who are the target of articles like this.

For example, the other day I was using THREE.js, and their docs have 3 different ways of using it:

<script src="js/three.js"></script>

or

npm install --save three
import * as THREE from 'three';

or

<script type="module">
import * as THREE from 'https://cdn.skypack.dev/three@<version>';
</script>

Which can be very confusing for devs who might not know the differences between them.

2

u/if-loop Apr 30 '21

What would be the simplest tooling to bundle stuff for modern Browsers that support modules?

So no Babel, no transpiling, no CJS etc.

5

u/MrJohz Apr 30 '21

Probably Parcel. It's designed to be a super-simple no-configuration bundler. You'll even get Babel, Typescript, and I think even some CSS bundling features for free.