[Pkg-javascript-devel] Questions about using ES modules in CJS.
Yadd
yadd at debian.org
Tue May 3 12:56:14 BST 2022
On 03/05/2022 13:15, Pirate Praveen wrote:
>
>
> On ചൊ, മേയ് 3 2022 at 06:41:01 വൈകു +0800 +0800, Ying-Chun Liu (PaulLiu)
> <paulliu at debian.org> wrote:
>> Hi Praveen,
>>
>> Sorry for bothering but I just got lots of questions about using ES
>> modules and I'm not sure who to ask. I tried to read the history of
>> Debian wiki pages about ES modules and found you.
>>
>>
>> Recently I've updated node-leven package to the latest upstream
>> version and it becomes an ES module now.
>> To use ES modules, I wrote a simple "mjs" script file:
>>
>> import leven from '/usr/share/nodejs/leven/index.js';
>> console.log(leven('test', 'test2')); // output: 1
>>
>>
>> The first question is why I cannot use "import leven from 'leven';"?
>>
> I think that is how ES module standard is supposed to work. You can add
> a symlink to node_modules
>
> mkdir -p node_modules
> ln -s /usr/share/nodejs/leven node_modules
>
> There is debian/nodejs/extlinks in pkg-js-tools to help with this
> symlink creation.
or by hand `pkgjs-ln leven`
> I think Jeremy Lal mentioned in the past that global path for ES modules
> will not be supported.
>> I got ERR_MODULE_NOT_FOUND if I don't use the full path.
>>
>> But packages like assert works without full path.
>> Not sure if I got things wrong.
>>
>>
>> The second question is more complicated.
>> I tried to use leven from a CJS module.
>> It works if I use dynamic import with full path:
>>
>> var leven;
>> async function test() {
>> leven = await import ('/usr/share/nodejs/leven/index.js');
>> leven = leven.default;
>> console.log(leven('test', 'test1')); // output 1
>> }
>> test();
>>
>> However, it seems to me that with CJS, there's no top-level await.
>> So I can only wrapping things in an async function.
Jest, await is available only in async functions. But for a simle
script, you can use zx which accepts await
>> But this is a bit trouble. How can I simply convert require('leven')
>> used in node-commist if there's no top-level await?
If leven is a pure ES module, you can build CJS files using `mjs2cjs -a`
in your debian/rules (it requires rollup and
node-rollup-plugin-node-resolve). This will modify package.json and
build a commonjs file, usable with require (tested, it works fine)
Then you can add a custom test:
$ cat >debian/tests/control <<EOF
Test-Command: cd / && node -e 'require("leven")'
Depends: @, nodejs
Features: test-name=commonjs
EOF
>> I cannot wrap whole node-commist inside an async function because it
>> should work like a library.
Then node-commist will work ;-)
More information about the Pkg-javascript-devel
mailing list