Reputation: 6819
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?
Upvotes: 4
Views: 2600
Reputation: 10215
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.
Upvotes: 3