[英]How can i use requier and import statments in node js , at the same file
我在处理节点 js 文件时遇到的问题是,我正在导入 readline 语句,并同时使用( 'type': 'module'
),想要同时使用两种方式而没有错误我如何在( readline ) 命令?
我面临的错误类型是:
SyntaxError: Cannot use import statement outside a module
我尝试在 (packag.json) 上使用模块,但随后请求者语句将面临类型错误,我无法 (transfare) ( import readline, { clearScreenDown } from "readline";
) 作为这样的请求者语句 ( const db = require('./dbConnection');
)
你不能,它们是互斥的。 import
是ESM (JavaScript 的原生指定模块系统), require
是CommonJS (Node.js 的旧模块系统)。
相反,您必须始终如一地使用 ESM 或 CommonJS。
如果您需要在 ESM 中进行动态(运行时确定)导入,您可以使用import()
伪函数,这有点像 CommonJS 的require
,只是它不会让调用代码等待,而是返回 promise。
答案取决于您要使用的方法的选择。
import ABC from 'ABC'
(节点核心模块或通过 npm 下载的包)const abc = require('./ABC')
用于您的自定义模块。 以下是示例。ABC.js
const ABC = ()=> {
return "ABC is called";
}
module.exports=ABC;
现在在你想要调用它的文件中。 index.js
const abc = require('./ABC');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.