Loading ES Modules in Node.js Projects

Loading ES Modules in Node.js Projects

4月 10, 2024 · 1 分钟阅读时长 · 111 字 · -阅读 -评论

Node.js supports ES module import. You can load ES modules through import, but there are some conditions. If not met, it will still throw errors.

https://static.1991421.cn/2024/2024-04-10-101444.jpeg

Note: import in Node.js differs from the browser side.

Import Local JS Modules

  1. Declare type:module in the package.json of the folder where the js file is located
  2. File extension should be mjs

Import URL

Executing import(url) in Node throws error ERR_UNSUPPORTED_ESM_URL_SCHEME

Error code explanation:

import with URL schemes other than file and data is unsupported.

From this, we can know that dynamic import in Node.js doesn’t support URLs. However, for example, Deno does support URLs, but Deno doesn’t consider CommonJS and doesn’t have this historical baggage.

Alan H
Authors
开发者,数码产品爱好者,喜欢折腾,喜欢分享,喜欢开源