giiker icon indicating copy to clipboard operation
giiker copied to clipboard

[Discussion] ESM vs. CJS

Open Scarygami opened this issue 6 years ago • 3 comments

Just curious why you decided to switch to CommonJS.

ESM is the agreed upon standard for modules in browsers, and already works in most modern browsers, whereas for CommonJS some build step is necessary to make it run in browsers.

I know that for node to work with ESM the file would need an .mjs extension, but in the current implementation this library works in browsers only anyway.

We could of course rename index.js to index.mjs with the caveat that some hosting solutions will serve the files with the wrong content-type.

Scarygami avatar Aug 27 '18 18:08 Scarygami

What we could do is to use index.mjs as ESM and compile this to index.js as you previously did, defining them in package.json like this:

{
  ...
  "main": "index.js",
  "module": "index.mjs"
  ...
}

Scarygami avatar Aug 27 '18 21:08 Scarygami

Well, I switched to CJS because my webpack build is broken. I don't want to break anything and there is no reason to use cutting edge technology if it works normally. I forgetting type="module" pattern.

The solution with main/module seems promising. My build works fine. I will review #4 and #5 and merge them within some days (Maybe I have to learn about Webpack ESM support and more). Anyway, sorry for the late reply.

hakatashi avatar Sep 10 '18 02:09 hakatashi

I did some testing myself and tooling support for .mjs files is still very limited and inconsistent. It might be better to use something like this instead, until there is a clear direction where .mjs is going:

{
  ...
  "main": "index.js",
  "module": "index.esm.js"
  ...
}

Scarygami avatar Sep 10 '18 12:09 Scarygami