最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ReferenceError: require is not defined in ES module - Stack Overflow

programmeradmin6浏览0评论

I'm trying to use the mand node index.js within the terminal to bring up the prompts I made and keep running into several errors, I looked them up on here seemingly fixed it and got another error. Maybe someone can point it out so I can save some time hopefully.. If you need more code details let me know.

Here is the ERROR in the terminal

$ 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"
  );
}

I'm trying to use the mand node index.js within the terminal to bring up the prompts I made and keep running into several errors, I looked them up on here seemingly fixed it and got another error. Maybe someone can point it out so I can save some time hopefully.. If you need more code details let me know.

Here is the ERROR in the terminal

$ 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"
  );
}
Share Improve this question asked Oct 20, 2022 at 3:27 user20071967user20071967 2
  • * I tried renaming like it said and it threw another error. – user20071967 Commented Oct 20, 2022 at 3:27
  • Ditch the require and use import. Simple as that. – Константин Ван Commented Dec 10, 2022 at 17:54
Add a ment  | 

2 Answers 2

Reset to default 2

do you have this line on your package.json ?

"type": "module"

if so, remove it and you can use require, but you'll get this error I believe:

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.

which I think it's related to the fact that The current version of inquirer is ONLY patible with an ESM import (using import), not from CommonJS modules using require().

UPDATE:

leave the

"type": "module" 

on you package.json and change the require for imports

instead of

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

change it to

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

You may need just to add

require.js

You can download it here

发布评论

评论列表(0)

  1. 暂无评论