3 ms·
ES Modules have an unfortunate syntax. I much prefer the function syntax to retrieving a module. >import {URLSearchParams} from "url"; >const {URLSearchParams}
by whoisstan 3y ago
ES Modules have an unfortunate syntax. I much prefer the function syntax to retrieving a module.
>import {URLSearchParams} from "url";
>const {URLSearchParams} = require("url");
or different destructuring from regular javascript
>import {URLSearchParams as P} from 'url';
>const {P: URLSearchParams} = require("url");
also you could have used await with require, it would be intuitive for developers as they likely have come across the same syntax before.
> const lib = await require("lib")
I don't see any argument why the require approach couldn't have been implemented in the browser. What is the actual gain from using ESModules syntax?
- WorldMaker 3y agoStatic analysis is ignored by the article here, but the import syntax requires all imports to be explicit. You can `require(someVariable)` but you cannot `import thing from someVariable`, that syntax is entirely not allowed. Similar to that is exports: the export syntax requires you to give static names for exports in a module. There is no `export [someVariable]` that can give a dynamic export name. The closest is `export default` which the import syntax treats as unnamed (and `(await import('module-name'))` calls `.default`). In CommonJS `module.exports[someVariable] = something` and worse `module.exports = { /* entirely dynamic object */ }` were extremely common. That sort of import/export static analysis is used for JIT compiler optimizations at run time in the browsers. That sort of import/export static analysis is used for safe tree-shaking at build time. (Yes, you can treeshake CommonJS, but it is dangerous and makes few guarantees that the final bundle is consistent/correct.) Yes, you can still dynamically `await import(someVariable)` but browsers don't optimize that in the same way (and bundlers don't treeshake that in the same way). That doesn't mean that it isn't very useful that the base case better supports static analysis and compiler optimizations and tree-shaking.