【问题标题】:How can i use requier and import statments in node js , at the same file我如何在节点 js 中使用 require 和 import 语句,在同一个文件中
【发布时间】:2022-01-10 23:21:15
【问题描述】:

我在处理节点 js 文件时遇到的问题是,我正在导入 readline statments 并同时使用 ('type': 'module'),想要同时使用这两种方式而没有错误 我如何在 (readline) 命令上使用 quier?
我面临的错误类型是:

SyntaxError: Cannot use import statement outside a module

我尝试在 (packag.json) 上使用模块,但随后请求者语句将面临类型错误 我不能(transfare)(import readline, { clearScreenDown } from "readline";)作为这样的请求者声明(const db = require('./dbConnection');

【问题讨论】:

    标签: javascript node.js module typeerror package.json


    【解决方案1】:

    你不能,它们是互斥的。 importESM(JavaScript 的原生、指定的模块系统),requireCommonJS(Node.js 的旧模块系统)。

    相反,您必须始终如一地使用 ESM 或 CommonJS。

    如果您需要在 ESM 中进行动态(运行时确定)导入,您可以使用 import() pseudo-function,这有点像 CommonJS require,只是它不是让调用代码等待,而是返回一个承诺.

    【讨论】:

      【解决方案2】:

      答案取决于您要使用的方法的选择。

      1. 使用import ABC from 'ABC'(节点核心模块或通过npm下载的包)
      2. 用户 const abc = require('./ABC') 用于您的自定义模块。以下是示例。

      ABC.js

      const ABC = ()=> {
       return "ABC is called";
      }
      module.exports=ABC;
      

      现在在你想要调用它的文件中。 index.js

      const abc = require('./ABC');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-27
        • 1970-01-01
        • 2021-11-01
        • 1970-01-01
        • 2020-04-12
        • 2021-04-09
        • 2022-07-14
        • 2020-11-06
        相关资源
        最近更新 更多