DEV Community

Cover image for Can I publish ES6 to npm?

Can I publish ES6 to npm?

stereobooster on June 09, 2019

Recently I wrote a small library for fun, which implements styled-components pattern for CSS Modules. I had a dilemma: how should I publish it, sh...
Collapse
 
thekashey profile image
Anton Korzunov

No you cant - there is no such thing as ES6.

What you can - you can publish as esmodules. These esmodules are not "ES Modules", aka import/export, but a special Babel target which targets some abstract browser, which does support these "ES Modules"(🤷‍♂️), plus stuff like async/await and generators(🔥), but not class members for example.

So - you can publish code in esmodules - import/export and language transpiled down to some "well-known" target. But any "special" babel plugin (or typescript) should do their job and disappear.

After publishing module that way you will have two problems:

  • running code in nodejs/jest - as you said nodejs does not support that stuff well. Use esm for node, and jest-transform for Jest. Drawback - first run, yet without a cache, might be very slow.
  • running code in a lower environment. Like IE11 if you still remember it. Personally I use devolution to de-evolute "ES6" bundle to whatever I need, adding all the polyfils by the way. Another way is to generate old and modern bundle, but that's not as easy.

So - as long as you are removing any "vendor specific" stuff(like stage-1 language features, or babel-plugins) from the package code - it would be ok 👍.

Parcel bundler and CRA would transpile everything automatically, out of the box.

Collapse
 
stereobooster profile image
stereobooster

This one may solve the problem github.com/WICG/import-maps#the-ba...

Collapse
 
jochemstoel profile image
Jochem Stoel

I believe there is no problem publishing ES6 as you call it on NPM. I post stuff all the time that uses ES10 or Electron specific features. Besides, NPM was never browser-only anyway. Lots of stuff needs to be compiled before even using it.
The most important thing is that your package adds value and that it contains a readme.md so people at least know how and in what context to use it.

Collapse
 
elliot profile image
Elliot

Here's a resource for npm + modules: pika.dev/cdn.

It's a CDN that serves npm modules as es6 modules! I haven't tried it out, but it seems pretty cool.

Collapse
 
stereobooster profile image
stereobooster

So I tried it. Indeed it solves the problem. My module is ES6 (unminified, with node-style module resolution), and it works in the browser as is.

Pika CDN transpiled it for me and changed import React from"react" to import React from"https://cdn.pika.dev/_/react/v16" 👌

Collapse
 
elliot profile image
Elliot

that is really cool. Thanks for trying it out and posting an update!

Collapse
 
stereobooster profile image
stereobooster

Yeah, I want to look into this one. Need some free time to read through

Collapse
 
stereobooster profile image
stereobooster