Error using Require and Xports

Asked

Viewed 229 times

0

I’m trying to make a require on JS but this giving error:

"Uncaught Referenceerror: require is not defined http://127.0.0.1:5500/js/access.js:1"

in access.js I made the following code:

const empresas = require('../api/empresa')

and in the enterprise.js

function empresa(){
    return `
    const nome = "Nome da empresa";
    const logo = "logo.png";
    const email = "[email protected]";
    `
}

module.exports = empresa

I wanted to do this with pure JS without anything, it’s like what I’m doing wrong?

1 answer

0

You wrote the code correctly maybe the problem is when finding the file in the directories.

you should use . / for the same directory

you must use .. / to return a directory from the current one

you must use .. /.. / to go back two directories from the current one and so on.

// index.js
const somar = require('./tool');

console.log(somar(2, 4));

// tool.js
function somar(value1, value2) {
  return value1 + value2;
}

module.exports = somar;

if you test this way the odis files in the main directory will work properly.

tip when you do Xports of functions prefer by:

Obs: you can export Anonimas functions I noomei them to be a little clearer.

// index.js
const { somar } = require('./tool');

console.log(somar(2, 4));

// tool.js
exports.somar = function somar(value1, value2) {
  return value1 + value2;
}

If in case you are making require on files for the browser you should imporar the javascript file in this way.

  • I found that the error is when I call the index.html page, which I may be doing wrong?

  • you have to import the script type module as a property. <script src="myscript.js" type="module"></script> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/M%C3%B3dulos , in which case you need to use import, export or export default

  • you can resolve your doubt in this post. https://answall.com/questions/213910/javascript-diff%C3%A7as-entre-import-e-require

Browser other questions tagged

You are not signed in. Login or sign up in order to post.