Dynamically importing CommonJS produces empty bundle
See original GitHub issueDynamically importing a commonjs module from a esmodule
asset produces an empty bundle.
<script type="module" src="./index.js"></script>
// index.js
import("./commonjs.js").then(v => console.log(v));
// commonjs.js
module.exports = 2;
Output (why is that even called ...exports
?):
var $c0ee4c22c4f80f14efb8476eb9807b50$exports = {};
$c0ee4c22c4f80f14efb8476eb9807b50$exports = import('' + './commonjs.e4b0f555.js');
$c0ee4c22c4f80f14efb8476eb9807b50$exports.then(v => console.log(v));
./commonjs.e4b0f555.js
is empty, without treeShake
, the output is
// ...
var $dfc1ea661454a5b57fd7e754dd151b32$exports = {};
$dfc1ea661454a5b57fd7e754dd151b32$exports = 2;
We check b.env.outputFormat === 'esmodule'
, but this value is just inherited from that parent asset.
The root cause is of course that we don’t/can’t translate commonjs to esmodules, but this is a case where this might be unexpected.
cc @devongovett
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (4 by maintainers)
Top Results From Across the Web
Dynamic loading of external modules in webpack fails
If you attempt to load something packed up as a CommonJS module, AMD, UMD, the import will succeed, but you will get an...
Read more >Modules • JavaScript for impatient programmers (ES2022 ...
some-module.mjs'; // Empty import (for modules with side effects) import '. ... For example, when npm creates an empty package inside a directory ......
Read more >How to Bundle JavaScript With Rollup — Step-by-Step Tutorial
Learn how to use Rollup as a smaller, more efficient alternative to webpack and Browserify to bundle JavaScript files in this step-by-step tutorial...
Read more >Dependency Pre-Bundling - Vite
Therefore, Vite must convert dependencies that are shipped as CommonJS or UMD into ESM first. When converting CommonJS dependencies, Vite performs smart import...
Read more >Introduction - rollup.js
Rollup can import existing CommonJS modules through a plugin. ... bundle when using dynamic imports --intro <text> Code to insert at top of...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
import()
returns the entire module namespace. Should we just map the common JSmodule.exports
object to that namespace if we detect it is CommonJS?Fixed by #3800