As of ES6 (ES2015), JavaScript supports a native module format. It uses the export and import keywords.

Import installed package

Depending on the structure of the module.

import * as foo from 'foo';

Or

import { foo } from 'foo';

Local modules

Note you must set this up otherwise you’ll get an error.

  • package.json
      {
      "type": "module"
      }
    

Named exports

  • foo.js
      function foo() {
        console.log("Hello");
      }
    
      export { foo };
    
  • foo.js alternative.
      export function foo() {
        console.log("Hello");
      }
    
import { foo } from './foo';

Default exports

  • foo.js
      function foo() {
        console.log("Hello");
      }
    
      export default foo;
    
import foo from './foo';