Cannot use ES6 import syntax in node
abulka opened this issue · comments
The recommended import syntax
import { Midi } from '@tonejs/midi'
works fine in the browser via snowpack or vite, however it fails via node v16.13.1
. Shouldn't it work in node, which now supports ES6 import syntax as long as you put everything in .mjs
files?
Repro
npm install @tonejs/midi
Then create a file main.mjs
import { Midi } from '@tonejs/midi'
console.log(Midi)
Running with node main.mjs
causes the error
import { Midi } from '@tonejs/midi'
^^^^
SyntaxError: Named export 'Midi' not found. The requested module '@tonejs/midi' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from '@tonejs/midi';
const { Midi } = pkg;
at ModuleJob._instantiate (node:internal/modules/esm/module_job:124:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:181:5)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
at async loadESM (node:internal/process/esm_loader:88:5)
at async handleMainPromise (node:internal/modules/run_main:65:12)
Also tried in the very latest node v18.0.0
and got the same error.
Interestingly the two step workaround suggested by node
import pkg from '@tonejs/midi';
const { Midi } = pkg;
works OK for node, but when serving the same file in a browser via vite
causes an "Cannot destructure property 'Midi' of 'pkg' as it is undefined."
error. Interestingly, serving the same file via snowpack works ok.
I finally found the following syntax which now happily works for node, vite and snowpack.
The secret seems to be to import * as pkg
and not doing what node says which is merely to import pkg
.
import * as pkg from '@tonejs/midi';
const { Midi } = pkg;
In other words, the same .mjs module can be run in node, e.g. running a mocha test or the module can be used as part of a browser based app and be served via vite or snowpack.