como usar correctamente el export in javascript

The export statement is used to export functions, objects or primitive values from a module so they can be used in other files or applications.

Here are some examples of how to use export in JavaScript:

Exporting a single function:

index.tsx
// export.js
function greet(name) {
  return `Hello, ${name}!`;
}
export { greet };
84 chars
6 lines

Importing a single function:

index.tsx
// index.js
import { greet } from './export.js';
console.log(greet('John')); // output: "Hello, John!"
103 chars
4 lines

Exporting multiple functions/objects:

index.tsx
// export.js
function sum(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

export { sum, subtract };
124 chars
11 lines

Importing multiple functions/objects:

index.tsx
// index.js
import { sum, subtract } from './export.js';
console.log(sum(3, 2)); // output: 5
console.log(subtract(3, 2)); // output: 1
136 chars
5 lines

Exporting a single object:

index.tsx
// export.js
const person = {
  name: 'John',
  age: 30,
  gender: 'male'
};

export default person;
101 chars
9 lines

Importing a single object:

index.tsx
// index.js
import person from './export.js';
console.log(person.name); // output: "John"
90 chars
4 lines

Note that the default keyword is used to export a single value from a module. Only one default export is allowed per module. When importing a module's default export, you can choose any name you like.

related categories

gistlibby LogSnag