raimohanska / lonna

A very popular library

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add ES module build

akheron opened this issue · comments

This makes webpack and other bundlers able to tree shake

Is there any reason to export as CJS at all these days? Should we go all ESM?

If we want both, what's the sensible way to dual-package in a tree-shakeable way?

I think it makes sense to have both commonjs and es modules with Lonna because node cannot handle es modules. Not having commonjs modules in Lonna would make it hard to run harmaja’s unit tests for example.

this in package.json: https://github.com/akheron/optics-ts/blob/master/package.json#L17-L19

@akheron Where did you find that Node.js supports package.json field called "module"?

"module": "./dist/esm/index.js"

Or is that field included in package.json for some other purpose?

I'd recommend instead to look at Conditional exports to specify CJS and ESM bundles.
I.e.

"exports": {
    "import": "./main-module.js",
    "require": "./main-require.cjs"
  },

Although they might not be supported in Node.js 10 LTS (which will become End-of-life status in April 2021 anyway)

That’s on the module field

Great, its for rollup! Found it's also supported by @rollup/plugin-node-resolve.

Note to myself: I do no longer need to use @rollup/importAlias and such to map my bare imports to the ES module files in rollup. 😃 Thanks @raimohanska !

So in conclusion conditional exports "exports": { "import: … } are just required to support importing ES modules from Node.js. Which I do in "isomorphic" (i.e. running insensitive of Node.js or browser) code.

Yeah, also webpack supports the module field.

I didn’t know about the conditional exports feature of node, and seems that webpack also supports it starting from v5.

It seems that it could actually be pretty safe to only build es modules as node 14 onwards seems to support them without any hassle. Just set type: “module” in package.json.

... or is the restriction still in place that you cannot import a commonjs module from an es module?