import from export default js code example

Example 1: node import all functions from file

//we are in ./utils/dbHelper.js, here we have some helper functions
function connect() {
  // connect do db...
}

function closeConnection() {
  // close connection to DB...
}

//let's export this function to show them to the world outside
module.exports = {
  connect(),
    closeConnection()
};

// now we are in ./main.js and we want use helper functions from dbHelper.js
const DbHelper = require ('./utils/dbHelper'); // import all file and name it DbHelper
DbHelper.connect(); // use function from './utils/dbHelper' using dot(.)

// or we can import only chosen function(s)
const { connect, closeConnection } = require ('./utils/dbHelper');
connect(); // use function from class without dot

Example 2: javascript export default

// Exporting individual features
export let name1, name2, …, nameN; // also var, const
export let name1 = …, name2 = …, …, nameN; // also var, const
export function functionName(){...}
export class ClassName {...}

// Export list
export { name1, name2, …, nameN };

// Renaming exports
export { variable1 as name1, variable2 as name2, …, nameN };

// Exporting destructured assignments with renaming
export const { name1, name2: bar } = o;

// Default exports
export default expression;
export default function (…) { … } // also class, function*
export default function name1(…) { … } // also class, function*
export { name1 as default, … };

// Aggregating modules
export * from …; // does not set the default export
export * as name1 from …;
export { name1, name2, …, nameN } from …;
export { import1 as name1, import2 as name2, …, nameN } from …;
export { default } from …;

Tags:

Misc Example