简体   繁体   English

Nodejs:仅在一个文件中使用导入

[英]Nodejs: use import in only one file

I have a project which is build using require, but now I need to use a package @nfteyez/sol-rayz, which only have support for ES6 import.我有一个使用 require 构建的项目,但现在我需要使用 package @nfteyez/sol-rayz,它只支持 ES6 导入。

I cannot add type: module because there are lots of files.我无法添加 type: module 因为有很多文件。

I have tried changing file to mjs, but I get errors when importing it with require in another file.我尝试将文件更改为 mjs,但在另一个文件中使用 require 导入它时出现错误。

I found in example that is possible when you enable module you can use import with:我在示例中发现,当您启用模块时,您可以使用 import:

// Define "require"
import { createRequire } from "module";
const require = createRequire(import.meta.url);

is there something similar for import?进口有类似的东西吗? I am using node v17我正在使用节点 v17

Go for dynamic import() function. Go 用于动态import() function。

let solRayz = await import('@nfteyez/sol-rayz');

For complete suppression and use one common style, it is very difficult as the implicit packages have their own module system in their package files.对于完全抑制和使用一种通用样式,这是非常困难的,因为隐式包在其 package 文件中有自己的模块系统。 For this particular problem, the following links might help对于这个特定问题,以下链接可能会有所帮助

Complete flexibility of using module systems is not available as of now目前尚不具备使用模块系统的完全灵活性

What is the difference between.js and.mjs files? .js 和.mjs 文件有什么区别?

https://nodejs.org/docs/latest/api/esm.html#esm_differences_between_es_modules_and_commonjs https://nodejs.org/docs/latest/api/esm.html#esm_differences_between_es_modules_and_commonjs

https://www.geeksforgeeks.org/how-to-use-an-es6-import-in-node-js/ https://www.geeksforgeeks.org/how-to-use-an-es6-import-in-node-js/

in node.js v14 and above, we can enable es module support by just add this in package.json在 node.js v14 及更高版本中,我们只需在package.json中添加即可启用 es 模块支持

"type": "module"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM