javascript - 引用错误: require is not defined in ES module

标签 javascript node.js inquirerjs

我正在尝试在终端中使用命令 node index.js 来显示我所做的提示,但不断遇到几个错误,我在这里查找了它们,似乎修复了它并遇到了另一个错误。也许有人可以指出这一点,这样我就可以节省一些时间。如果您需要更多代码详细信息,请告诉我。

这是终端中的错误

$ node index.js
file:///C:/Users/Owner/bootcamp/homework/10-team-profile-generator/index.js:2
const fs = require('fs');
           ^

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and 'C:\Users\Owner\bootcamp\homework\10-team-profile-generator\package.json' 
contains "type": "module". To treat it as a CommonJS 
script, rename it to use the '.cjs' file extension.  
    at ←[90mfile:///C:/Users/Owner/bootcamp/homework/10-team-profile-generator/←[39mindex.js:2:12
←[90m    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)←[39m
    at async Promise.all (index 0)
←[90m    at async ESMLoader.import (node:internal/modules/esm/loader:533:24)←[39m
←[90m    at async loadESM (node:internal/process/esm_loader:91:5)←[39m
←[90m    at async handleMainPromise (node:internal/modules/run_main:65:12)←[39m

INDEX.JS

// node modules
const fs = require('fs');
const inquirer = require('inquirer')
const generateTeam = require("./src/template.js");

// lib modules
const Engineer = require("./lib/employee");
const Intern = require("./lib/intern");
const Manager = require("./lib/manager");

// Array for answers to questions
const newStaffMemberData = [];

// Array object questions asked in CLI to user
const questions = async () => {
  const answers = await inquirer
    .prompt([
      {
        type: "input",
        message: "What is your name?",
        name: "name",
      },
      {
        type: "input",
        message: "What is your ID number?",
        name: "id",
      },
      {
        type: "input",
        message: "What is your email?",
        name: "email",
      },
      {
        type: "list",
        message: "What is your role?",
        name: "role",
        choices: ["Engineer", "Intern", "Manager"],
      },
    ])


    
    //  console.log(answers);
      // if manager selected, answer these specific question
      if (answers.role === "Manager") {
        const managerAns = await inquirer
          .prompt([
            {
              type: "input",
              message: "What is your office number",
              name: "officeNumber",
            },
          ])
          const newManager = new Manager(
            answers.name,
            answers.id,
            answers.email,
            managerAns.officeNo
          );
          newStaffMemberData.push(newManager);
          
        // if engineer selected answer these set of questions
      } else if (answers.role === "Engineer") {
        const githubAns = await inquirer
          .prompt([
            {
              type: "input",
              message: "What is your GitHub user name?",
              name: "github",
            }
          ])
            const newEngineer = new Engineer(
              answers.name,
              answers.id,
              answers.email,
              githubAns.github
            );
            newStaffMemberData.push(newEngineer);
          
        // if intern selected answer these set of questions
      } else if (answers.role === "Intern") {
        const internAns = await inquirer
          .prompt([
            {
              type: "input",
              message: "What university did you attend?",
              name: "school",
            },
          ])
          
          const newIntern = new Intern(
            answers.name,
            answers.id,
            answers.email,
            internAns.school
          );
          newStaffMemberData.push(newIntern);          
      } 

}; //end of questions function

async function promptQuestions() {
  await questions()
    
  
  const addMemberAns = await inquirer
    .prompt([
      {
        name:'addMember',
        type: 'list',
        choices: ['Add a new member', 'Create team'],
        message: "What would you like to do next?"
      }
    ])

    if (addMemberAns.addMember === 'Add a new member') {
      return promptQuestions()
    }
    return createTeam();
}  

promptQuestions();

function createTeam () {
  console.log("new guy", newStaffMemberData)
  fs.writeFileSync(
    "./output/index.html",
    generateTeam(newStaffMemberData),
    "utf-8"
  );
}

最佳答案

你的 package.json 上有这一行吗?

"type": "module"

如果是这样,请将其删除,然后您可以使用 require,但我相信您会收到此错误:

Error [ERR_REQUIRE_ESM]: require() of ES Module /home/flaalf/self/sandbox/node_modules/inquirer/lib/inquirer.js from /home/flaalf/self/sandbox/index.js not supported. Instead change the require of inquirer.js in /home/flaalf/self/sandbox/index.js to a dynamic import() which is available in all CommonJS modules.

我认为这与当前版本的询问器仅与 ESM 导入(使用导入)兼容,而不是与使用 require() 的 CommonJS 模块兼容这一事实有关。

更新:

离开

"type": "module" 

在 package.json 上更改导入要求

而不是

const fs = require("fs")
const inquirer = require("inquirer")

更改为

import fs from "fs";
import inquirer from "inquirer";

关于javascript - 引用错误: require is not defined in ES module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74134116/

相关文章:

node.js - NPM 在 OSX 10.9.5 上安装 zmq 失败

javascript - 在 InquirerJS 中传递选择的答案?

javascript - 如何根据chartjs中的标签值更改条形颜色

javascript - jQuery 表循环?

javascript - 带有 Material-UI 的 SSR 上的@emotion/cache 总是空的

javascript - 在 iframe 中预览 pdf 的一部分?

node.js - 如何在不重新启动的情况下重新加载 Node-RED 中的 Node ?

node.js - 通过NodeJS客户端创建时间戳