I'm probably just incorrect about my assumptions of how this should work, so I would appreciate it if somebody can either tell me what to change in my Rollup config or how I should use the resulting bundle.
Let me set the scene. I'm writing a library, bundling it with Rollup, and then want to write some HTML page where I import a named export from that libray. It keeps telling me that it can't find the named export.
For your convenience, I have boiled the issue down to this minimal example:
I have The following files in my project folder:
min-example.js
:export function minExample(){
return "can you find me?";
}
package.json
:{
"name": "min-example",
"version": "1.0.0",
"description": "A minimal example of an issue with rollup",
"scripts": {
"build": "rollup -c"
},
"author": "nvcleemp",
"license": "ISC",
"devDependencies": {
"rollup": "^2.58.0"
}
}
rollup.config.js
export default [
{
input: "min-example.js",
output: {
file: `min-example.bundle.js`,
name: "min-example",
format: "umd"
}
}
];
If I run npm run build
, then this creates the file min-example.bundle.js
:
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["min-example"] = {}));
})(this, (function (exports) { 'use strict';
function minExample(){
return "can you find me?";
}
exports.minExample = minExample;
Object.defineProperty(exports, '__esModule', { value: true });
}));
I would have expected that I could use this file in the following manner:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Minimum example</title>
</head>
<body>
<script type="module">
import { minExample } from './min-example.bundle.js';
console.log(minExample());
</script>
</body>
</html>
As I said above however, this complains that it can't find the named export minExample
.
Note that it does work without using Rollup:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Minimum example</title>
</head>
<body>
<script type="module">
import { minExample } from './min-example.js';
console.log(minExample());
</script>
</body>
</html>
OK, a bit more trial-and-error let to a solution. Apparently the output format should be es
instead of umd
, so the file rollup.config.js
had to be changed to
export default [
{
input: "min-example.js",
output: {
file: `min-example.bundle.js`,
name: "min-example",
format: "es"
}
}
];
So I was indeed under the false impression that umd
just combined es
and cjs
.