Why don't use require instead?
OskarKaminski opened this issue · comments
Both Node and Webpack implements either ES6 module loaders, and CommonJS.
Whenever you can, you should use static module loading, and when you need to load dynamic module, just use require(...)
as all developers were doing for years.
Why another syntax? What problems it solves that CommonJS doesn't?
require
isn't part of the language; only node implements it. What would browsers use, if they don't want to force a build step?
Ok, I wasn't aware it's already possible to import modules without any module bundler. But I see it's possible with import
. Thanks.
If not require
, is there another way to import a class? It seems like import * as module from 'module'
disallows new module()
(“TypeError: module is not a constructor”). I’m trying to import p5.js. import p5 from 'p5'
works as well as const p5 = require('p5')
, but import('https://cdn.jsdelivr.net/npm/p5@1.0.0/lib/p5.js').then(p5 => {new p5(…)})
fails the same way import * as p5 from 'p5'
does. (I’m using parcel that offers dynamic imports)
import * as
brings in a module namespace object, so that’ll never be useful for anything except a container of the real things you want. In your case, try .then(({ default: p5 }) => new p5())
Thank you very much for the very quick answer! That solved it!