4

I want to create an npm library that delivers modules using ES import/export instead of commonjs (like for example lodash-es does). If I'm not mistaken, the delivered code must be ES5 and has import/export.

I can't figure out how to configure Babel to do that. I expect that the option targets.esmodules should do the trick.

When I have the following code in calc.js:

// calc.js export function add (a, b) { const result = a + b return result } 

and babel configuration .babelrc:

{ "presets": [ [ "@babel/preset-env", { "targets": { "esmodules": true } } ] ] } 

When running babel:

babel calc.js 

The output is:

"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.add = add; function add(a, b) { var result = a + b; return result; } 

Which is commonjs (exports.add). The option targets.esmodules seems to have no effect. How can I get Babel to generate an es module (export function add)? Or am I misunderstanding the idea of delivering ES modules on npm?

2
  • "If I'm not mistaken, the delivered code must be ES5 and has import/export." - you probably are mistaken there. Any environment that understands import/export does also understand all the other ES6 syntax, so this requirement is really weird. Commented Aug 3, 2019 at 14:46
  • Thanks. That was my assumption too, but I get quite some issues reported for mathjs. JS projects normally never transpile code from dependencies, only from the source of a project itself. So it gives issues when I publish a library that needs transpilation. Looking at redux, the es folder contains es import/export and the code is transpiled ES5 (no =>, const, etc). Same with lodash-es. How to achieve that with Babel? Commented Aug 4, 2019 at 8:40

1 Answer 1

3

It looks like based on the Rollup docs that you should indeed transpile a version that has only import/export, but has transpiled out all of the other non-ES5 syntax. The Webpack docs say something similar. This format assumes that your users are using tools like Rollup or Webpack, which natively support import/export statements, but then presumably transpile them to an ES5 compatible syntax without needing to run your library through Babel.

And it looks like Redux in particular pulls this off by using the Rollup format option and then in their .babelrc file they use the "modules": false option to tell Babel not to transpile module statements. It's not clear to me how Lodash manages it, since looking over their source code I don't see any build scripts anywhere in the repo.

Sign up to request clarification or add additional context in comments.

1 Comment

Yippie, that's indeed the missing link, thanks a ton Robert for figuring this out! I've a proof of concept working now with Babel config {"presets": [["@babel/preset-env", { "modules": false }]]}.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.