javascript logo

Import/Export Statements

The import and export statements help share JavaScript functions across multiple files. The use of these statements helps to keep code manageable and reuseable. Manageable because you don't have to import/export every function. Reusable because you can import the same functionality into differnt files across your project.

Import

Syntax:

import defaultExport from "module-name";

Where defaultExport is the name of the export being used and "module-name" is where the functions is coming from. The "module-name" can be a relative path "./some-js-file.js" or the name of a downloaded bundle:

import SyntaxHighlighter from 'react-syntax-highlighter';

If you want to import everything from a module you use the * (asterisk).

//import * name from 'file-name'
import * as products from './products.js';

If you want to import multipe functions, but not all you use {} (curly braces)

import {remove, add} from '/my-file.js';

Sometimes you need to rename an export becuase the name is too long

import {
removeSomethingFromTheProductData as remove, 
addSomethingFromTheProductData as add
} from '/product.js';

Export

There are two types of exports

  1. Named Exports (zero or more exports per module)
  2. Default Exports (one per module)

Syntax:

//Named
export const data = str.split('');
export function getSomeData(){...};

//Default
export {aFunction as default};
export default aFunction;
export default class { .. };
import React from 'react';
import Layout from '../components/layout';
import SEO from '../components/seo';

const NotFoundPage = () => (
  <Layout>
    <SEO title='404: Not found' />
    <h1>NOT FOUND</h1>
    <p>You just hit a route that doesn&#39;t exist... the sadness.</p>
  </Layout>
)

export default NotFoundPage

Putting it all together

//water-bottle.js module
const productName = "water bottle";
const productDescription = "a container that is used to hold water.";

const waterBottle = {
  productName,
  productDescription
};

export default waterBottle;

//products.js import module
import {waterBottle as wb} from '/water-bottle.js';
console.log(wb);
//{productName: "water bottle", productDescription:"a container that is used to hold water."}