I was just going through this library HERE (glide.js) , as i was checking the package.json file i see the following command under the key scripts
:
"build:esm": "rollup --config build/esm.js && rollup --config build/esm.modular.js",
What exactly is this script doing ? I know a a config file is being passed to rollup.js here, but whats with the .esm
? when i see the dist/ folder i also see a glide.esm.js
file , what exactly is this file doing ?
The build config file for esm looks like below:
import build from './build'
export default Object.assign(build, {
input: 'entry/entry-complete.js',
output: Object.assign(build.output, {
file: 'dist/glide.esm.js',
format: 'es'
})
})
But i don't quite understand what the format: 'es'
really means here. Basically to break it down , what is the difference between the glide.js
and the glide.esm.js
file in the dist/
folder ?
format: 'es'
tells rollup that it should output the bundle in an ECMAScript Module aware way. This means that it should create a bundle that can be import
ed using something along the lines of:
import Glide from "some/place/glide/is/hosted/glide.js
If the context that this script is used in is not ESM aware, you will get syntax errors. In that case, it makes more sense to use a UMD rollup bundle because it is the most compatible version of the bundle.
Explaining UMD in depth is beyond the scope of this question, but suffice it to say that it makes the bundle able to work with AMD and CommonJS aware loaders as well as populating a global namespace with the bundle's exports.
Additionally, for browsers that do not understand what ES modules are or would throw syntax errors if they tried to parse them, you can include a fallback script that would leverage the UMD or bundle of another format using a script of form: <script src="some/non/esm/script.js" nomodule="true" />
which would tell an ESM aware context that it shouldn't run the linked script.
Consider the following snippet which should work in Firefox and Chrome since they support ESM modules. Stack Overflow snippets do not have a way to load modules so you will need to put together a small project using the following code:
import Glide from "https://unpkg.com/@glidejs/[email protected]/dist/glide.esm.js";
new Glide(".glide").mount();
<!DOCTYPE html>
<html lang="en">
<head>
<title>Module Demo</title>
<link rel="stylesheet" href="https://unpkg.com/@glidejs/[email protected]/dist/css/glide.core.min.css" />
<link rel="stylesheet" href="https://unpkg.com/@glidejs/[email protected]/dist/css/glide.theme.min.css" />
<script type="module" src="demo.js"></script>
</head>
<body>
<main>
<div class="glide">
<div data-glide-el="track" class="glide__track">
<ul class="glide__slides">
<li class="glide__slide">Foo</li>
<li class="glide__slide">Bar</li>
<li class="glide__slide">Fizz</li>
</ul>
</div>
</div>
</main>
</body>
</html>